from __future__ import annotations

import json
import sys
from pathlib import Path
from typing import Any

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

from epione_templates import load_template_data, validate_template_data


def write_json(path: Path, value: Any) -> None:
    path.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8")


def export_schema(data: dict[str, Any], output_dir: Path) -> None:
    output_dir.mkdir(parents=True, exist_ok=True)
    forms = data.get("forms", [])
    product_library = data.get("product_library", {})

    write_json(
        output_dir / "template_meta.json",
        {
            "version": data.get("version"),
            "generated_at": data.get("generated_at"),
            "clinic_context": data.get("clinic_context", {}),
            "defaults_precedence": data.get("defaults_precedence"),
        },
    )
    write_json(output_dir / "conditions.json", data.get("conditions", []))
    write_json(output_dir / "forms.json", forms)
    write_json(output_dir / "global_defaults.json", data.get("global_defaults", {}))
    write_json(
        output_dir / "per_form_defaults.json",
        {
            form["form_id"]: form.get("defaults") or form.get("procedure_defaults") or {}
            for form in forms
        },
    )
    write_json(
        output_dir / "fields.json",
        [
            {"form_id": form.get("form_id"), **field}
            for form in forms
            for field in form.get("fields", [])
        ],
    )
    write_json(
        output_dir / "picklists.json",
        [
            {
                "form_id": form.get("form_id"),
                "field_key": field.get("key"),
                "options": [
                    option.strip()
                    for option in str(field.get("options", "")).split(";")
                    if option.strip()
                ],
            }
            for form in forms
            for field in form.get("fields", [])
            if str(field.get("options", "")).strip()
        ],
    )
    write_json(output_dir / "source_urls.json", data.get("source_urls", {}))
    write_json(output_dir / "product_library.json", product_library.get("product_rows", []))
    write_json(
        output_dir / "product_default_profiles.json",
        product_library.get("product_default_profiles", []),
    )
    write_json(
        output_dir / "verification_workflow.json",
        product_library.get("verification_workflow", []),
    )


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

    export_schema(data, ROOT / "src" / "schema")
    print(f"Wrote normalized schema files to {ROOT / 'src' / 'schema'}")
    return 0


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