#!/usr/bin/env python3
"""Create the exact selected BeamNG part/body index without requiring Blender."""
from __future__ import annotations

import argparse
import json
from pathlib import Path

from beamng_jbeam import (JBeamDocumentCache, build_part_catalog, build_selected_part_index,
                          preselect_configuration, resolve_part_closure, selected_part_summary,
                          write_bound_selected_part_index)


def choose_configuration(vehicle_root: Path, candidate: str, hint: str | None) -> Path:
    selected = preselect_configuration(vehicle_root, [candidate], hint)
    if selected is not None:
        return selected
    raise ValueError("source GLB import requires an unambiguous selected .pc configuration or configuration hint")


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--source-root", required=True)
    parser.add_argument("--vehicle-root", required=True)
    parser.add_argument("--candidate", required=True)
    parser.add_argument("--configuration-hint")
    parser.add_argument("--configuration")
    parser.add_argument("--common-root", action="append", default=[])
    parser.add_argument("--bridge-plan-key", required=True)
    parser.add_argument("--source-sha", required=True)
    parser.add_argument("--common-closure")
    parser.add_argument("--output", required=True)
    args = parser.parse_args()

    source_root = Path(args.source_root).resolve()
    vehicle_root = Path(args.vehicle_root).resolve()
    dependency_roots = [Path(value).resolve() for value in args.common_root]
    requested_configuration = Path(args.configuration) if args.configuration else \
        choose_configuration(vehicle_root, args.candidate, args.configuration_hint)
    if requested_configuration.is_symlink():
        raise ValueError("selected configuration must not be a symlink")
    configuration_path = requested_configuration.resolve()
    try:
        configuration_path.relative_to(vehicle_root)
    except ValueError as error:
        raise ValueError("selected configuration escapes vehicle root") from error
    cache = JBeamDocumentCache(source_root, dependency_roots)
    ranked_roots = [(vehicle_root, 0), (source_root / "vehicles" / "common", 1),
                    *((root / "vehicles" / "common", 2) for root in dependency_roots)]
    admitted = [(root, rank) for root, rank in ranked_roots if root.is_dir()]
    catalog, failures = build_part_catalog(
        [root for root, _ in admitted], cache, [rank for _, rank in admitted])
    configuration = cache.load(configuration_path)
    if configuration.get("format") != 2 or not isinstance(configuration.get("parts"), dict):
        raise ValueError("selected BeamNG configuration must be format 2 with a parts object")
    main_part = configuration.get("mainPartName") or configuration.get("model") or args.candidate
    closure = resolve_part_closure(catalog, configuration["parts"], main_part)
    index = build_selected_part_index(args.candidate, configuration_path, closure, cache, catalog)
    index["parseFailures"] = failures[:20]
    index["parseCounts"] = {f"{cache.receipt(path)['root']}:{cache.receipt(path)['path']}": count
                            for path, count in sorted(cache.parse_counts.items(), key=lambda row: str(row[0]))}
    receipt = write_bound_selected_part_index(index, args.output, args.bridge_plan_key,
                                              args.source_sha, args.common_closure)
    print(json.dumps(selected_part_summary(index, receipt), sort_keys=True,
                     separators=(",", ":"), ensure_ascii=False))


if __name__ == "__main__":
    main()
