from __future__ import annotations

import argparse
import json
from datetime import datetime, UTC
from pathlib import Path
from typing import Any, Dict

from db.brochure_sku_vocabulary import build_brochure_sku_vocabulary


def export_brochure_sku_vocabulary(*, pdf_folder: str, output_path: str) -> Dict[str, Any]:
    pdf_dir = Path(pdf_folder)
    pdf_paths = sorted(path for path in pdf_dir.glob("*.pdf") if path.is_file())
    vocabulary = build_brochure_sku_vocabulary(pdf_paths)
    vocabulary["generated_at_utc"] = datetime.now(UTC).isoformat()
    vocabulary["pdf_folder"] = str(pdf_dir)
    vocabulary["pdf_files"] = [path.name for path in pdf_paths]

    out_path = Path(output_path)
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(json.dumps(vocabulary, indent=2), encoding="utf-8")
    return {
        "status": "ok",
        "output_path": str(out_path),
        "source_pdf_count": vocabulary["source_pdf_count"],
        "type_count": vocabulary["type_count"],
    }


def main() -> None:
    parser = argparse.ArgumentParser(description="Export brochure-derived SKU vocabulary from brochure PDFs.")
    parser.add_argument("--pdf-folder", required=True, help="Folder containing brochure PDFs.")
    parser.add_argument("--output", required=True, help="Output JSON path.")
    args = parser.parse_args()

    result = export_brochure_sku_vocabulary(
        pdf_folder=args.pdf_folder,
        output_path=args.output,
    )
    print(json.dumps(result, indent=2))


if __name__ == "__main__":
    main()
