# mascaret_to_mage.py -- Pamhyr
# Copyright (C) 2026  INRAE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

# -*- coding: utf-8 -*-
#!/bin/env python3

import sys
import importlib.util as imp
import os
import numpy as np

def lire_opt(filename, res):
    with open(filename, encoding = "ISO-8859-1", mode ="r") as f:
        variables = ['"t"','"Bief"','"Section"','"Pk"']
        lines = f.readlines()
        for start,line in enumerate(lines):
            print("line n "+str(start)+" : ",line)
            if line == "[variables]\n": continue
            if line == "[resultats]\n": break
            val = line.split(';')
            variables.append(val[1])
            if val[1] == '"ZREF"': izref = start+3
            if val[1] == '"Q"': iq = start+3
            if val[1] == '"Z"': iz = start+3
        print ("variables : "+str(variables))

        #resultats
        res.mage_version = 83
        # first pass to count sect and biefs
        prev_timestep = float(lines[start+1].split(';')[0])
        for line in lines[start+1:]:
            ls = line.split(';')
            t = float(ls[0])
            if prev_timestep != t : break
            ibief = int(ls[1].strip('"'))
            isect = int(ls[2].strip('"'))
            pk = float(ls[3])
            if ibief > res.ibmax:
                res.ibmax += 1
                res.is1.append(isect)
                res.is2.append(isect)
            if isect > res.ismax:
                res.ismax += 1
                res.xgeo.append(pk)
                res.ygeo.append(0.0)
                res.zfd.append(float(ls[izref]))
                res.ybas.append(0.0)
            if isect > res.is2[ibief-1]:
                res.is2[ibief-1] = isect
            if isect < res.is1[ibief-1]:
                res.is1[ibief-1] = isect

        print(" nb sections : "+str(res.ismax))

        # first pass to get the data
        prev_bief = 0
        prev_sect = 0
        z = np.zeros(res.ismax, dtype=np.float32)
        q = np.zeros(res.ismax, dtype=np.float32)
        isect = 0
        count = np.array([1],dtype=np.int32)
        bZ = bytearray('Z'.encode())
        bQ = bytearray('Q'.encode())
        for line in lines[start+1:]:
            ls = line.split(';')
            t = float(ls[0])
            ibief = int(ls[1].strip('"'))
            isect = int(ls[2].strip('"'))
            if prev_timestep != t :
                res.values['Z'].append(prev_timestep, z)
                res.values['Q'].append(prev_timestep, q)
                count[0] = 4 + 8 + 1 + 8*len(z)
                res.raw_data.append(count)
                res.raw_data.append(np.array([len(z)],dtype=np.int32))
                res.raw_data.append(np.array([prev_timestep],dtype=np.float64))
                res.raw_data.append(np.array(bZ,dtype=np.byte))
                res.raw_data.append(z)
                res.raw_data.append(count)
                res.raw_data.append(count)
                res.raw_data.append(np.array([len(q)],dtype=np.int32))
                res.raw_data.append(np.array([prev_timestep],dtype=np.float64))
                res.raw_data.append(np.array(bQ,dtype=np.byte))
                res.raw_data.append(q)
                res.raw_data.append(count)
                prev_timestep = t
            z[isect-1] = float(ls[iz])
            q[isect-1] = float(ls[iq])


if __name__ == "__main__":

    current_dir = os.getcwd()
    os.chdir('/home/theophile.terraz/Codes/mage/src')
    spec = imp.spec_from_file_location("me", "./mage_extraire.py")
    me = imp.module_from_spec(spec)
    spec.loader.exec_module(me)
    os.chdir(current_dir)

    print( 'Number of arguments:', len(sys.argv), 'arguments.')
    print( 'Argument List:', str(sys.argv))
    res = me.data()
    lire_opt(sys.argv[1], res)
    res.write_bin_8(sys.argv[2][0:-4])
