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

import argparse
import subprocess
import sys


def run(cmd: list[str]) -> subprocess.CompletedProcess:
    return subprocess.run(cmd, text=True, capture_output=True, check=False)


def require(cond: bool, msg: str, failures: list[str]):
    if not cond:
        failures.append(msg)


def main() -> int:
    failures: list[str] = []

    # 1) Command exposure
    help_root = run([sys.executable, "-m", "macer.cli.phonopy_main", "-h"])
    require(help_root.returncode == 0, "root help command failed", failures)
    root_text = help_root.stdout + help_root.stderr
    require("qscaild" in root_text, "qscaild command is not exposed in CLI help", failures)

    # 2) qscaild parser options
    help_qs = run([sys.executable, "-m", "macer.cli.phonopy_main", "qscaild", "-h"])
    require(help_qs.returncode == 0, "qscaild -h failed", failures)
    qs_text = help_qs.stdout + help_qs.stderr
    for opt in [
        "--nconf",
        "--nfits",
        "--memory",
        "--mixing",
        "--tolerance",
        "--use-pressure",
        "--pressure-diag",
        "--dry-run",
    ]:
        require(opt in qs_text, f"missing qscaild option in help: {opt}", failures)

    # 3) Parser defaults via dry-run (no expensive calculation)
    dry = run(
        [
            sys.executable,
            "-m",
            "macer.cli.phonopy_main",
            "qscaild",
            "-p",
            "README.md",  # intentionally invalid structure file for a parse-only check
            "-T",
            "300",
            "--dry-run",
        ]
    )
    # Expect non-zero because README.md is not a valid structure, but parser+dispatch must run.
    out = (dry.stdout or "") + (dry.stderr or "")
    require(
        ("Dry-run enabled." in out) or ("not a valid POSCAR/CIF" in out) or ("Error" in out),
        "qscaild dispatch did not execute as expected in dry-run path",
        failures,
    )

    if failures:
        print("qSCAILD validation: FAILED")
        for item in failures:
            print(f"- {item}")
        return 1

    print("qSCAILD validation: PASSED")
    return 0


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

