"""Seed canonical collection filter profiles from brochure JSON files."""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path
from typing import Iterable, List

from db.collection_filter_profile_seed import load_brochure_payload, seed_collection_filter_profiles
from db.session import get_session


def _iter_paths(args: argparse.Namespace) -> List[Path]:
    paths: List[Path] = []
    for raw in args.file or []:
        path = Path(raw)
        if path.is_file():
            paths.append(path)
    if args.folder:
        folder = Path(args.folder)
        if folder.is_dir():
            paths.extend(sorted(folder.glob("*.json")))
    seen = set()
    unique: List[Path] = []
    for path in paths:
        key = str(path.resolve())
        if key in seen:
            continue
        seen.add(key)
        unique.append(path)
    return unique


def main() -> int:
    parser = argparse.ArgumentParser(description="Seed collection filter profiles from brochure JSON files")
    parser.add_argument("--file", action="append", default=None, help="One brochure JSON file; repeatable")
    parser.add_argument(
        "--folder",
        default=r"E:\2026\plytixmage_dbs_data\Brochure_Data",
        help="Folder containing brochure JSON files",
    )
    parser.add_argument("--create-missing-registry", action="store_true")
    parser.add_argument("--no-overwrite", action="store_true")
    parser.add_argument("--apply", action="store_true", help="Write updates")
    args = parser.parse_args()

    paths = _iter_paths(args)
    payloads = [load_brochure_payload(path) for path in paths]
    with get_session() as session:
        result = seed_collection_filter_profiles(
            session,
            payloads,
            overwrite=not args.no_overwrite,
            create_missing_registry=args.create_missing_registry,
            dry_run=not args.apply,
        )
        result["files"] = [str(path) for path in paths]
        if args.apply:
            session.commit()
    print(json.dumps(result, indent=2, default=str))
    return 0


if __name__ == "__main__":
    sys.exit(main())
