#!/opt/venv/bin/python
"""Small SPR-KKR SCF stand-in used by the Docker integration tests."""

import re
import shutil
import sys
import time
from pathlib import Path

# This test executable runs under the container's venv, while ASE2SPRKKR is
# mounted from the host (a source checkout or an installed-wheel layout).
# Keep this path adjustment local to the test executable.
sys.path[:0] = ["/workspace/ase2sprkkr/src", "/workspace/ase2sprkkr"]
import ase2sprkkr


POTFIL_RE = re.compile(
    r"\bPOTFIL\s*=\s*(?:\"([^\"]+)\"|'([^']+)'|([^\s]+))",
    re.IGNORECASE,
)
NITER_RE = re.compile(r"\bNITER\s*=\s*(\d+)", re.IGNORECASE)
ITERATION_START_RE = re.compile(r"(?=^.*\bEMIN\s+=)", re.MULTILINE)
SCF_OUTPUT = Path(ase2sprkkr.__file__).resolve().parent / "outputs" / "examples" / "scf.out"


def _requested_iterations(parameters):
    match = NITER_RE.search(parameters)
    return int(match.group(1)) if match else 1


def _output_for_iterations(count):
    output = SCF_OUTPUT.read_text()
    parts = ITERATION_START_RE.split(output)
    prefix, iterations = parts[0], parts[1:]

    if count < 1:
        raise ValueError(f"NITER must be positive, got {count}")
    if count > len(iterations):
        raise ValueError(
            f"Test SCF fixture has only {len(iterations)} iterations, "
            f"but NITER={count} was requested"
        )

    selected = iterations[:count]
    if any("SPRKKR-run for:" not in iteration for iteration in selected):
        raise RuntimeError("SCF test fixture does not contain complete iterations")
    return prefix + "".join(selected)


def main():
    parameters = sys.stdin.read()
    match = POTFIL_RE.search(parameters)
    if match is None:
        raise RuntimeError("SCF test input does not contain CONTROL.POTFIL")

    potfil = next(value for value in match.groups() if value is not None)
    potential = Path(potfil)
    if not potential.is_file():
        raise FileNotFoundError(f"Input potential was not staged: {potential}")

    output = _output_for_iterations(_requested_iterations(parameters))

    # Delay the first output as a real remote calculation would, then keep a
    # deliberate gap after the first line. The latter makes it deterministic
    # that the client can observe live output while the process is still alive.
    time.sleep(0.25)
    lines = iter(output.splitlines(keepends=True))
    first_line = next(lines)
    sys.stdout.write(first_line)
    sys.stdout.flush()
    time.sleep(1.0)

    for line in lines:
        sys.stdout.write(line)
        sys.stdout.flush()

    # KKRSCF writes the updated potential only after the SCF run completes.
    shutil.copyfile(potential, Path(str(potential) + "_new"))


if __name__ == "__main__":
    main()
