from __future__ import annotations

import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))

from epione_templates import approval_findings, approval_summary, load_template_data, validate_template_data
from epione_templates.product_verification import findings_to_csv
from epione_templates.artifacts import write_v07_outputs


def main() -> int:
    data = load_template_data()
    errors = validate_template_data(data)
    if errors:
        for error in errors:
            print(error)
        return 1

    output_dir = ROOT / "output" / "v0.7"
    output_dir.mkdir(parents=True, exist_ok=True)
    generated_outputs = write_v07_outputs(ROOT, output_dir, data)
    live_sheet_url_path = ROOT / "Google_Sheets" / "LIVE_GOOGLE_SHEET_URL.txt"
    if live_sheet_url_path.exists():
        generated_outputs["live_google_sheet_url"] = live_sheet_url_path.read_text(
            encoding="utf-8"
        ).strip()
    clasp_config_path = ROOT / "Google_Sheets" / "apps_script" / ".clasp.json"
    if clasp_config_path.exists():
        clasp_config = json.loads(clasp_config_path.read_text(encoding="utf-8"))
        generated_outputs["apps_script_project_id"] = clasp_config.get("scriptId", "")
    manifest = {
        "source_version": data.get("version"),
        "forms": len(data.get("forms", [])),
        "conditions": len(data.get("conditions", [])),
        "product_default_approval": approval_summary(data),
        "generated_outputs": generated_outputs,
        "status": "v0.7_outputs_with_clinician_html_app",
        "next_generators": ["live_google_sheets_menu_smoke", "emr_paste_test"],
    }
    (output_dir / "build_manifest.json").write_text(
        json.dumps(manifest, indent=2) + "\n",
        encoding="utf-8",
    )
    (output_dir / "product_default_approval_dashboard.csv").write_text(
        findings_to_csv(approval_findings(data)),
        encoding="utf-8",
    )
    print(f"Wrote {output_dir / 'build_manifest.json'}")
    print(f"Wrote {output_dir / 'product_default_approval_dashboard.csv'}")
    return 0


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