#!/usr/bin/env python3
from __future__ import annotations

import argparse
from pathlib import Path


def parse_parameters(path: Path) -> dict[str, str]:
    data: dict[str, str] = {}
    for line in path.read_text().splitlines():
        line = line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        k, v = line.split("=", 1)
        data[k.strip()] = v.strip()
    return data


def map_to_macer_cli(params: dict[str, str]) -> list[str]:
    mapped = []
    if "T_K" in params:
        mapped += ["-T", params["T_K"]]
    if "nconf" in params:
        mapped += ["--nconf", params["nconf"]]
    if "nfits" in params:
        mapped += ["--nfits", params["nfits"]]
    if "memory" in params:
        mapped += ["--memory", params["memory"]]
    if "mixing" in params:
        mapped += ["--mixing", params["mixing"]]
    if "tolerance" in params:
        mapped += ["--tolerance", params["tolerance"]]
    if "pdiff" in params:
        mapped += ["--pdiff", params["pdiff"]]
    if "grid" in params:
        mapped += ["--grid", params["grid"]]
    if "imaginary_freq" in params:
        mapped += ["--imaginary-freq", params["imaginary_freq"]]
    if params.get("use_smalldisp", "False").lower() in ("true", "1", "yes"):
        mapped += ["--use-smalldisp"]
    if "use_pressure" in params:
        mapped += ["--use-pressure", params["use_pressure"]]
    if "pressure_diag" in params:
        vals = [x.strip() for x in params["pressure_diag"].split(",")]
        if len(vals) == 3:
            mapped += ["--pressure-diag", vals[0], vals[1], vals[2]]
    return mapped


def main() -> int:
    parser = argparse.ArgumentParser(description="Compare qscaild-master parameter files with macer qscaild option mapping.")
    parser.add_argument("--root", default="qscaild-master/test_dir", help="Path to qscaild reference test_dir.")
    args = parser.parse_args()

    root = Path(args.root).resolve()
    if not root.exists():
        print(f"Reference root not found: {root}")
        return 1

    files = sorted(root.rglob("parameters"))
    if not files:
        print(f"No 'parameters' files found under: {root}")
        return 1

    print(f"Found {len(files)} parameter files under {root}")
    print("")
    for p in files:
        params = parse_parameters(p)
        mapped = map_to_macer_cli(params)
        rel = p.relative_to(root)
        print(f"[{rel}]")
        print("  qscaild params:")
        for key in ["T_K", "nconf", "nfits", "memory", "mixing", "tolerance", "pdiff", "grid", "imaginary_freq", "use_pressure", "pressure_diag", "use_smalldisp"]:
            if key in params:
                print(f"    {key} = {params[key]}")
        print("  macer qscaild suggestion:")
        if mapped:
            print("    macer phonopy qscaild -p POSCAR " + " ".join(mapped) + " --dry-run")
        else:
            print("    (no mapped options)")
        print("")

    print("Done.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

