from __future__ import annotations

import json
from pathlib import Path

from config.client import ODataClient, extract_entity_sets, utc_now_iso
from config.settings import LOGS_DIR, load_settings


def main() -> int:
    settings = load_settings()
    client = ODataClient(settings)

    LOGS_DIR.mkdir(parents=True, exist_ok=True)

    try:
        metadata_xml = client.fetch_metadata()
    except Exception as exc:
        print(f"[error] failed to fetch metadata: {exc}")
        return 1

    metadata_file = LOGS_DIR / "metadata.xml"
    metadata_file.write_text(metadata_xml, encoding="utf-8")

    try:
        entity_sets = extract_entity_sets(metadata_xml)
    except Exception as exc:
        print(f"[error] metadata fetched, but parse failed: {exc}")
        return 1

    summary = {
        "generated_at": utc_now_iso(),
        "service_root": settings.service_root,
        "metadata_url": settings.metadata_url,
        "entity_set_count": len(entity_sets),
        "entity_sets": entity_sets,
    }

    entity_sets_file = LOGS_DIR / "entity_sets.json"
    entity_sets_file.write_text(
        json.dumps(summary, ensure_ascii=False, indent=2),
        encoding="utf-8",
    )

    print(f"[ok] metadata saved: {metadata_file}")
    print(f"[ok] entity sets saved: {entity_sets_file}")
    print(f"[ok] total entity sets: {len(entity_sets)}")
    return 0


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

