#!/usr/bin/env python3
"""Query the unified 1C object route index by GUID or name fragment."""

from __future__ import annotations

import argparse
import json
from pathlib import Path
from typing import Any


def load_json(path: Path) -> dict[str, Any]:
    return json.loads(path.read_text(encoding="utf-8-sig"))


def normalize(value: str) -> str:
    return value.casefold().replace(" ", "")


def compact(item: dict[str, Any]) -> dict[str, Any]:
    return {
        "guid": item["guid"],
        "route_kind": item.get("route_kind") or [],
        "dbnames": item.get("dbnames") or [],
        "xml_top_objects": item.get("xml_top_objects") or [],
        "xml_occurrence_count": item.get("xml_occurrence_count"),
        "config_routes": item.get("config_routes") or [],
        "extension_routes": item.get("extension_routes") or [],
    }


def find_by_name(objects: dict[str, Any], name: str, limit: int) -> list[dict[str, Any]]:
    wanted = normalize(name)
    hits = []
    for item in objects.values():
        for top in item.get("xml_top_objects") or []:
            values = [top.get("name") or "", top.get("synonym") or "", top.get("relative_path") or ""]
            if any(wanted in normalize(value) for value in values):
                hits.append(item)
                break
        if len(hits) >= limit:
            break
    hits.sort(
        key=lambda item: (
            not any(normalize(top.get("name") or "") == wanted for top in item.get("xml_top_objects") or []),
            (item.get("xml_top_objects") or [{}])[0].get("relative_path") or "",
        )
    )
    return hits[:limit]


def main() -> int:
    parser = argparse.ArgumentParser(description="Query a 1C unified route index.")
    parser.add_argument("--index", type=Path, required=True)
    parser.add_argument("--guid")
    parser.add_argument("--name")
    parser.add_argument("--limit", type=int, default=20)
    parser.add_argument("--output", type=Path)
    args = parser.parse_args()

    index = load_json(args.index)
    objects = index.get("objects") or {}
    if args.guid:
        item = objects.get(args.guid.lower())
        result = {"schema": "onec_route_query.v1", "query": {"guid": args.guid}, "matches": [compact(item)] if item else []}
    elif args.name:
        matches = [compact(item) for item in find_by_name(objects, args.name, args.limit)]
        result = {"schema": "onec_route_query.v1", "query": {"name": args.name}, "matches": matches}
    else:
        raise SystemExit("Use --guid or --name.")

    text = json.dumps(result, ensure_ascii=False, indent=2) + "\n"
    if args.output:
        args.output.parent.mkdir(parents=True, exist_ok=True)
        args.output.write_text(text, encoding="utf-8")
        print(json.dumps({"output": str(args.output), "matches": len(result["matches"])}, ensure_ascii=False))
    else:
        print(text)
    return 0


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