from __future__ import annotations

import json
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]


def main() -> int:
    program = (ROOT / "src/dotnet/QuantEngine.Web/Program.cs").read_text(encoding="utf-8")
    csproj = (ROOT / "src/dotnet/QuantEngine.Infrastructure/QuantEngine.Infrastructure.csproj").read_text(encoding="utf-8")
    migration = ROOT / "src/dotnet/QuantEngine.Infrastructure/Migrations/V5__Add_Normalized_Learning_History.sql"
    orchestrator = ROOT / "src/dotnet/QuantEngine.Application/Services/KisDataCollectionOrchestrator.cs"
    seed_service = ROOT / "src/dotnet/QuantEngine.Application/Services/JsonSeedIngestionService.cs"
    checks = {
        "dotnet_collector_registered": "ICollectionOrchestrator, KisDataCollectionOrchestrator" in program,
        "postgres_repository_registered": (
            "ICollectionReadRepository" in program and "ICollectionWriteRepository" in program
        ),
        "json_seed_registered": "JsonSeedIngestionService" in program,
        "dbup_v5_embedded": "Migrations/**/*.sql" in csproj and migration.exists(),
        "orchestrator_present": orchestrator.exists(),
        "json_seed_ingestion_present": seed_service.exists(),
        "json_artifact_contract": "KIS_DOTNET_COLLECTION_V1" in orchestrator.read_text(encoding="utf-8"),
        "no_xlsx_in_seed_service": ".xlsx" not in seed_service.read_text(encoding="utf-8"),
    }
    gate = "PASS" if all(checks.values()) else "FAIL"
    payload = {"formula_id": "DOTNET_POSTGRESQL_JSON_CUTOVER_V1", "gate": gate, "checks": checks}
    output = ROOT / "Temp/dotnet_postgresql_json_cutover_v1.json"
    output.parent.mkdir(parents=True, exist_ok=True)
    output.write_text(json.dumps(payload, indent=2), encoding="utf-8")
    print(json.dumps(payload, indent=2))
    return 0 if gate == "PASS" else 1


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