from __future__ import annotations

import json
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
FILES = [
    ROOT / "src/dotnet/QuantEngine.Web/Program.cs",
    ROOT / ".gitea/workflows/deploy-prod.yml",
    ROOT / "src/dotnet/QuantEngine.Web/appsettings.json",
    ROOT / "src/dotnet/QuantEngine.Web/appsettings.Development.json",
]
REPORT = ROOT / "Temp/runtime_connection_settings_immutability_v1.json"


def main() -> int:
    violations: list[str] = []
    for path in FILES:
        text = path.read_text(encoding="utf-8", errors="replace")
        if "Environment.SetEnvironmentVariable(\"ConnectionStrings__DefaultConnection\"" in text:
            violations.append(f"runtime_write:{path.relative_to(ROOT)}")
    payload = {
        "formula_id": "RUNTIME_CONNECTION_SETTINGS_IMMUTABILITY_V1",
        "gate": "PASS" if not violations else "FAIL",
        "setting_key": "ConnectionStrings__DefaultConnection",
        "source": "external_runtime_settings",
        "violations": violations,
    }
    REPORT.parent.mkdir(parents=True, exist_ok=True)
    REPORT.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps(payload, ensure_ascii=False, indent=2))
    return 0 if payload["gate"] == "PASS" else 1


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