#!/usr/bin/env python3
"""Ejecuta SC1/SD2 (Novender) y exporta POS4 al formato .simul de Simusol."""
import argparse
from array import array
from collections import defaultdict
from dataclasses import dataclass
import math
import os
from pathlib import Path
import re
import shlex
import shutil
import struct
import subprocess
import sys
import tempfile

ROOT = Path(__file__).resolve().parents[1]
EXTENSIONS = (".simul", ".dirac", ".ls1", ".ls2", ".log")


@dataclass
class Vector:
    name: str
    component: str
    values: array


def read_pos4(path):
    """POST guarda REAL*4: datos seguidos por minimo y maximo (no muestras)."""
    groups = defaultdict(list)
    size = path.stat().st_size
    with path.open("rb") as stream:
        header = stream.read(2048)
        if len(header) != 2048:
            raise ValueError("directorio POS4 incompleto")
        endian = None
        for order in ("<", ">"):
            name, stamp, kind, length, record = struct.unpack_from(order + "12s11sbii", header)
            if name.rstrip() == b"DIRECTORY" and kind == 0 and length == 2048 and record == 1:
                endian = order
                break
        if endian is None:
            raise ValueError("el archivo no es POS4 de SCEPTRE2 (directorio incompatible)")
        names = set()
        regions = []
        for i in range(1, 64):
            raw, stamp, kind, length, record = struct.unpack_from(endian + "12s11sbii", header, i * 32)
            if kind == -1:
                break
            if kind in (0, 1):
                continue
            if kind == 9 and raw.rstrip() == b"HEADING":
                continue
            if kind != 4:
                raise ValueError("tipo POS4 no admitido para resultados: " + str(kind))
            label = raw.decode("ascii").rstrip()
            if len(label) != 8 or label[7] not in "0123456789" or label[6] not in "_AIDR":
                raise ValueError("nombre de vector SCEPTRE2 no reconocido: " + repr(label))
            if label in names:
                raise ValueError("vector duplicado: " + label)
            names.add(label)
            start, end = (record - 1) * 2048, (record - 1) * 2048 + length * 4
            if length < 3 or record < 2 or end > size:
                raise ValueError("vector vacio o truncado: " + label)
            if any(start < b and a < end for a, b in regions):
                raise ValueError("vectores POS4 superpuestos")
            regions.append((start, end))
            stream.seek(start)
            values = array("f")
            values.frombytes(stream.read(length * 4))
            if values.itemsize != 4:
                raise ValueError("esta plataforma no usa float de 32 bits")
            if (sys.byteorder == "little") != (endian == "<"):
                values.byteswap()
            del values[-2:]
            if not all(math.isfinite(x) for x in values):
                raise ValueError("resultado no finito en " + label)
            groups[int(label[7])].append(Vector(label[:6].strip(), label[6], values))
    if not groups:
        raise ValueError("el archivo no contiene resultados numericos")
    for run, vectors in groups.items():
        axes = [v for v in vectors if v.name in ("TIME", "FREQ") and v.component in ("_", "A")]
        if len(axes) != 1:
            raise ValueError(f"corrida {run}: se esperaba un solo eje TIME o FREQ")
        axis = axes[0]
        if any(len(v.values) != len(axis.values) for v in vectors):
            raise ValueError(f"corrida {run}: las columnas tienen longitudes distintas")
        groups[run] = [axis] + [v for v in vectors if v is not axis]
    return dict(sorted(groups.items()))


def column_names(vectors):
    labels = []
    for v in vectors:
        if v.component == "_" or v.name in ("TIME", "FREQ"):
            label = v.name
        elif v.component == "A":
            complex_pair = any(w.name == v.name and w.component == "I" for w in vectors)
            label = v.name + ("_RE" if complex_pair else "_MOD")
        else:
            label = v.name + {"I": "_IM", "D": "_DEG", "R": "_RAD"}[v.component]
        labels.append(label)
    if len(labels) != len(set(labels)):
        raise ValueError("nombres de columnas duplicados")
    return labels


def write_simul(path, groups, source):
    def row(items):
        return "".join(f"{v:>24}" for v in items) + "\n"

    with path.open("w", encoding="utf-8") as stream:
        for run, vectors in groups.items():
            labels = column_names(vectors)
            axis = labels[0]
            variables = [("tiempo" if x == "TIME" else "frecuencia" if x == "FREQ" else x.lower())
                         for x in labels]
            magnitudes = [("tiempo" if axis == "TIME" else "frecuencia")] + ["??"] * (len(labels) - 1)
            # TIME puede estar escalado por el modelo: no inventar unidades fisicas.
            units = ["??"] * len(labels)
            stream.write("#   Producido por sceptre2simul a partir de " + source.name.replace("\n", " ") + "\n")
            stream.write("#   Datos POS4 REAL*4; 9 cifras significativas; sin minimo/maximo finales.\n")
            stream.write(f"#  RERUN {run} ({len(vectors[0].values)} puntos)\n")
            stream.write("#  para Simusol: sceptrevars variables magnitudes unidades\n")
            for fields in (labels, variables, magnitudes, units):
                stream.write("#" + row(fields)[1:])
            for values in zip(*(v.values for v in vectors)):
                stream.write(row([format(x, ".9g") for x in values]))
            stream.write("\n\n")


def free_output(requested):
    for n in range(1000000):
        candidate = requested if n == 0 else requested.with_name(requested.stem + f"-{n}.simul")
        if not any(os.path.lexists(candidate.with_suffix(ext)) for ext in EXTENSIONS):
            return candidate
    raise ValueError("no se encuentra un nombre libre para la salida")


def publish(source, destination):
    """Publicar completo y sin reemplazar un archivo existente, incluso con carreras."""
    with tempfile.NamedTemporaryFile(dir=destination.parent, prefix=".sceptre2-", delete=False) as tmp:
        staging = Path(tmp.name)
        try:
            with source.open("rb") as stream:
                shutil.copyfileobj(stream, tmp)
        except BaseException:
            staging.unlink()
            raise
    try:
        os.link(staging, destination)
    finally:
        staging.unlink()


def run_command(command, directory, log, timeout):
    log.write("\n$ " + shlex.join(str(x) for x in command) + "\n")
    log.flush()
    result = subprocess.run([str(x) for x in command], cwd=directory, stdin=subprocess.DEVNULL,
                            stdout=log, stderr=subprocess.STDOUT, timeout=timeout)
    if result.returncode:
        raise RuntimeError(f"{Path(command[0]).name} termino con codigo {result.returncode}")


def simulate(args, source, work):
    root = args.sceptre_dir.resolve()
    model = (args.modelos or root / "lib/modellib.dat").resolve()
    library = (args.biblioteca or root / "lib/usrlib.a").resolve()
    for needed in (root / "bin/sceptreM", root / "lib/sceptreDU.o", root / "lib/libsceptreDU.a", model, library):
        if not needed.is_file():
            raise ValueError(f"falta {needed}; compilar SCEPTRE2 con make install")
    shutil.copyfile(source, work / "input.dat")
    shutil.copyfile(model, work / "modellib.dat")
    reserved = {"input.dat", "modellib.dat", "pgmsave.for", "datasave.dat", "acsave.dat",
                "sceptreDU", "sceptre.lis", "fort.7", "salida.simul", "corrida.log", "fase1.lis", "fase2.lis"}
    for data in args.dato:
        data = data.resolve()
        if data.name in reserved or data.name.startswith("fort.") or (work / data.name).exists():
            raise ValueError("nombre de dato reservado o repetido: " + data.name)
        shutil.copyfile(data, work / data.name)
    extras = [p.resolve() for p in args.fuente]
    # La distribucion usa c11.f90, c12.f90 y g02.f90 junto al .d.
    for suffix in (".f90",):
        companion = source.with_suffix(suffix)
        if companion.is_file() and companion != source and companion not in extras:
            extras.append(companion)
    functions = source.parent / "funciones.for"
    if functions.is_file() and functions not in extras:
        extras.append(functions)
    with (work / "corrida.log").open("w", encoding="utf-8") as log:
        try:
            run_command([root / "bin/sceptreM"], work, log, args.timeout)
        finally:
            if (work / "sceptre.lis").exists():
                (work / "sceptre.lis").rename(work / "fase1.lis")
        program = work / "pgmsave.for"
        if not program.is_file() or not program.stat().st_size:
            raise RuntimeError("la fase 1 no genero pgmsave.for; revisar .ls1")
        command = [args.fc, "-std=legacy", "-fno-automatic", "-fdollar-ok", "-Wno-line-truncation",
                   "-I", root / "x2", "-I", source.parent, "-o", work / "sceptreDU", program, *extras,
                   root / "lib/sceptreDU.o", library, root / "lib/libsceptreDU.a", "-ltabular2", "-llapack", "-lblas", "-lumfpack",
                   *args.enlazar]   # -ltabular2: ETABLE/XTABLE de x2 (defecto 64)
        run_command(command, work, log, args.timeout)
        try:
            run_command([work / "sceptreDU"], work, log, args.timeout)
        finally:
            if (work / "sceptre.lis").exists():
                (work / "sceptre.lis").rename(work / "fase2.lis")
    if not (work / "fort.7").is_file():
        raise RuntimeError("SCEPTRE2 no produjo datos POS4; revisar .ls2 (una corrida solo de condiciones iniciales no genera series)")
    listing = (work / "fase2.lis").read_text(errors="replace").upper()
    if listing.count("BEGIN POST PROCESSING") != listing.count("END OF POST PROCESSING"):
        raise RuntimeError("postprocesamiento incompleto; revisar .ls2")
    if "NO DC STEADY STATE SOLUTION" in listing:
        raise RuntimeError("fallo la solucion estacionaria; revisar .ls2")
    return work / "fort.7"


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("entrada", type=Path, help="circuito .d (con o sin extension), .sceptre, o .dirac para convertir")
    output = parser.add_mutually_exclusive_group()
    output.add_argument("-o", "--directorio", type=Path, default=Path.cwd(), help="directorio de salida; predeterminado: actual")
    output.add_argument("--salida", type=Path, help="nombre .simul; si existe se agrega -1, -2, etc.")
    parser.add_argument("--sceptre-dir", type=Path, default=ROOT, help="raiz de la instalacion SC1/SD2")
    parser.add_argument("-m", "--modelos", type=Path, help="biblioteca modellib.dat")
    parser.add_argument("-u", "--biblioteca", type=Path, help="biblioteca Fortran usrlib.a")
    parser.add_argument("--fuente", type=Path, action="append", default=[], help="fuente Fortran adicional; repetible")
    parser.add_argument("--dato", type=Path, action="append", default=[], help="copiar un dato auxiliar al temporal; repetible")
    parser.add_argument("--enlazar", action="append", default=[], help="opcion adicional de enlace, por ejemplo --enlazar=-lm")
    parser.add_argument("--fc", default="gfortran", help="compilador Fortran")
    parser.add_argument("--timeout", type=float, default=300, help="limite en segundos por fase (300)")
    parser.add_argument("--conservar", action="store_true", help="conservar el directorio de trabajo, tambien ante errores")
    args = parser.parse_args(argv)
    work = None
    result = None
    try:
        source = args.entrada.expanduser().resolve()
        if not source.exists() and source.suffix == "":
            source = source.with_suffix(".d")
        if not source.is_file():
            raise ValueError("no existe la entrada: " + str(source))
        if not math.isfinite(args.timeout) or args.timeout <= 0:
            raise ValueError("--timeout debe ser positivo y finito")
        requested = args.salida or args.directorio / (source.stem + ".simul")
        requested = requested.expanduser().absolute()
        if requested.suffix != ".simul":
            raise ValueError("--salida debe terminar en .simul")
        requested.parent.mkdir(parents=True, exist_ok=True)
        result = free_output(requested)
        work = Path(tempfile.mkdtemp(prefix="sceptre2simul-"))
        binary = source if source.suffix.lower() == ".dirac" else simulate(args, source, work)
        groups = read_pos4(binary)
        write_simul(work / "salida.simul", groups, source)
        if binary != source:
            publish(binary, result.with_suffix(".dirac"))
        publish(work / "salida.simul", result)
        print(result)
        print("{} corrida(s), {} filas; binario conservado en {}".format(
            len(groups), sum(len(v[0].values) for v in groups.values()),
            source if binary == source else result.with_suffix(".dirac")), file=sys.stderr)
        return 0
    except (OSError, ValueError, RuntimeError, subprocess.TimeoutExpired) as exc:
        print("sceptre2simul: " + str(exc), file=sys.stderr)
        return 1
    finally:
        if work is not None:
            try:
                for name, ext in (("corrida.log", ".log"), ("fase1.lis", ".ls1"), ("fase2.lis", ".ls2")):
                    if (work / name).is_file():
                        publish(work / name, result.with_suffix(ext))
                if result is not None and (work / "corrida.log").exists():
                    print("Diagnosticos: " + str(result.with_suffix(".log")), file=sys.stderr)
            except OSError as exc:
                args.conservar = True
                print("No se pudieron guardar diagnosticos: " + str(exc), file=sys.stderr)
            if args.conservar:
                print("Directorio de trabajo: " + str(work), file=sys.stderr)
            else:
                shutil.rmtree(work)


if __name__ == "__main__":
    sys.exit(main())
