"""Trusted local MathorCup check. Run: python environment-check.py --output mathorcup-environment.json"""
from __future__ import annotations
import argparse
import importlib
import importlib.util
import json
import os
import shutil
import subprocess
import sys
import tempfile
from datetime import datetime, timezone
from pathlib import Path

MODULES = ["numpy", "pandas", "scipy", "sklearn", "matplotlib", "xgboost", "cvxpy", "ortools", "openpyxl"]
TOOLS = ["python", "pandoc", "typst", "xelatex", "pdflatex", "mmdc", "drawio"]


def run_check():
    report = {"format": "zhenzhi-mathorcup-environment-v1", "checked_at": datetime.now(timezone.utc).isoformat(), "python": sys.version.split()[0], "modules": {}, "tools": {}, "smoke": {}}
    for module in MODULES:
        report["modules"][module] = {"available": importlib.util.find_spec(module) is not None}
    for tool in TOOLS:
        report["tools"][tool] = {"available": shutil.which(tool) is not None}
    with tempfile.TemporaryDirectory(prefix="mathorcup-check-", dir=Path.cwd()) as temp:
        root = Path(temp)
        if report["modules"]["pandas"]["available"] and report["modules"]["openpyxl"]["available"]:
            try:
                pd = importlib.import_module("pandas")
                source = pd.DataFrame({"x": [1, 2, 3], "y": [2, 4, 6]})
                xlsx = root / "smoke.xlsx"
                source.to_excel(xlsx, index=False)
                back = pd.read_excel(xlsx)
                report["smoke"]["excel_roundtrip"] = {"passed": back.equals(source), "detail": "write and read 3 rows"}
            except Exception as exc:
                report["smoke"]["excel_roundtrip"] = {"passed": False, "detail": str(exc)}
        else:
            report["smoke"]["excel_roundtrip"] = {"passed": False, "detail": "pandas or openpyxl missing"}
        if report["modules"]["sklearn"]["available"]:
            try:
                from sklearn.linear_model import LinearRegression
                model = LinearRegression().fit([[1], [2], [3]], [2, 4, 6])
                prediction = float(model.predict([[4]])[0])
                report["smoke"]["regression"] = {"passed": abs(prediction - 8) < 1e-9, "detail": f"prediction={prediction:g}"}
            except Exception as exc:
                report["smoke"]["regression"] = {"passed": False, "detail": str(exc)}
        else:
            report["smoke"]["regression"] = {"passed": False, "detail": "scikit-learn missing"}
        if report["modules"]["matplotlib"]["available"]:
            try:
                matplotlib = importlib.import_module("matplotlib")
                matplotlib.use("Agg")
                pyplot = importlib.import_module("matplotlib.pyplot")
                fig, ax = pyplot.subplots()
                ax.plot([1, 2, 3], [2, 4, 6])
                target = root / "smoke.png"
                fig.savefig(target)
                pyplot.close(fig)
                report["smoke"]["plot_png"] = {"passed": target.is_file() and target.stat().st_size > 100, "detail": "PNG generated"}
            except Exception as exc:
                report["smoke"]["plot_png"] = {"passed": False, "detail": str(exc)}
        else:
            report["smoke"]["plot_png"] = {"passed": False, "detail": "matplotlib missing"}
        if report["tools"]["pandoc"]["available"] and (report["tools"]["xelatex"]["available"] or report["tools"]["pdflatex"]["available"]):
            try:
                source = root / "smoke.md"
                output = root / "smoke.pdf"
                source.write_text("# MathorCup environment check\n\nA small PDF test.\n", encoding="utf-8")
                engine = "xelatex" if report["tools"]["xelatex"]["available"] else "pdflatex"
                result = subprocess.run(["pandoc", str(source), "-o", str(output), "--pdf-engine", engine], capture_output=True, text=True, timeout=60, check=False)
                report["smoke"]["pdf"] = {"passed": result.returncode == 0 and output.is_file(), "detail": (result.stderr[-500:] or "PDF generated") if result.returncode else "PDF generated"}
            except Exception as exc:
                report["smoke"]["pdf"] = {"passed": False, "detail": str(exc)}
        elif report["tools"]["typst"]["available"]:
            try:
                source = root / "smoke.typ"
                output = root / "smoke.pdf"
                source.write_text("= MathorCup environment check\nA small PDF test.", encoding="utf-8")
                result = subprocess.run(["typst", "compile", str(source), str(output)], capture_output=True, text=True, timeout=60, check=False)
                report["smoke"]["pdf"] = {"passed": result.returncode == 0 and output.is_file(), "detail": (result.stderr[-500:] or "PDF generated") if result.returncode else "PDF generated"}
            except Exception as exc:
                report["smoke"]["pdf"] = {"passed": False, "detail": str(exc)}
        else:
            report["smoke"]["pdf"] = {"passed": False, "detail": "Pandoc+LaTeX or Typst missing"}
    return report


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", default="mathorcup-environment.json")
    args = parser.parse_args()
    path = Path(args.output).resolve()
    path.write_text(json.dumps(run_check(), ensure_ascii=False, indent=2), encoding="utf-8")
    print(f"Wrote {path}")
