"""Focused tests for deterministic BeamNG part-graph indexing."""
from __future__ import annotations

import importlib.util
import json
import math
import os
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch

sys.path.insert(0, str(Path(__file__).resolve().parent))

import beamng_jbeam
from beamng_jbeam import (
    JBeamDocumentCache,
    bounded_asset_paths,
    build_part_catalog,
    build_selected_part_index,
    decode_jbeam_table,
    normalize_jbeam,
    resolve_part_closure,
    stable_json_sha256,
    write_bound_selected_part_index,
)


def load_lowerer():
    module_path = Path(__file__).with_name("lower-beamng.py")
    spec = importlib.util.spec_from_file_location("lower_beamng_test", module_path)
    if spec is None or spec.loader is None:
        raise RuntimeError("could not load BeamNG lowerer")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


class JBeamPartGraphTests(unittest.TestCase):
    def test_state_rows_persist_and_inline_options_do_not(self) -> None:
        rows = decode_jbeam_table([
            ["id:", "x", "y"],
            {"nodeWeight": 10},
            ["a", 1, 2],
            ["b", 3, 4, {"nodeWeight": 20, "collision": False}],
            ["c", 5, 6],
        ])
        self.assertEqual(rows, [
            {"nodeWeight": 10, "id": "a", "x": 1, "y": 2},
            {"nodeWeight": 20, "collision": False, "id": "b", "x": 3, "y": 4},
            {"nodeWeight": 10, "id": "c", "x": 5, "y": 6},
        ])

    def test_cache_closure_and_index_are_source_bound(self) -> None:
        with tempfile.TemporaryDirectory() as temporary:
            root = Path(temporary)
            vehicle = root / "vehicles" / "car"
            vehicle.mkdir(parents=True)
            (vehicle / "car.jbeam").write_text(json.dumps({
                "car": {
                    "slotType": "main",
                    "slots": [["type", "default"], ["car_engine", "engine_stock"]],
                    "flexbodies": [["mesh", "group"], {"deformGroup": "shell"}, ["body", []]],
                },
                "engine_stock": {
                    "slotType": "car_engine",
                    "props": [["func", "mesh"], ["engine", "engine_mesh", {"optional": True}]],
                },
                "engine_race": {"slotType": "car_engine"},
            }))
            configuration = vehicle / "race.pc"
            configuration.write_text(json.dumps({
                "format": 2, "model": "car", "parts": {"car_engine": "engine_race"}
            }))

            cache = JBeamDocumentCache(root)
            catalog, failures = build_part_catalog([vehicle], cache)
            # Repeated reads are object-identical and never parse the file twice.
            self.assertEqual(cache.parse_counts[(vehicle / "car.jbeam").resolve()], 1)
            graph = resolve_part_closure(catalog, cache.load(configuration)["parts"])
            index = build_selected_part_index("car", configuration, graph, cache, catalog)

            self.assertEqual(failures, [])
            self.assertEqual(index["selectedBodies"], ["car", "engine_race"])
            self.assertEqual(index["slotClosure"][0]["selection"], "override")
            self.assertEqual(index["parts"][0]["body"]["flexbodies"][1], {"deformGroup": "shell"})
            self.assertEqual(index["configuration"]["path"], "vehicles/car/race.pc")
            self.assertEqual(index["configurationSha256"], index["configuration"]["sha256"])
            self.assertEqual(max(cache.parse_counts.values()), 1)
            self.assertEqual(stable_json_sha256(index), stable_json_sha256(index))

    def test_ambiguous_part_definitions_are_rejected(self) -> None:
        with tempfile.TemporaryDirectory() as temporary:
            root = Path(temporary)
            first, second = root / "vehicles" / "first", root / "vehicles" / "second"
            first.mkdir(parents=True)
            second.mkdir(parents=True)
            (first / "a.jbeam").write_text('{"shared":{"slotType":"main"}}')
            (second / "b.jbeam").write_text('{"shared":{"slotType":"main"}}')
            cache = JBeamDocumentCache(root)
            with self.assertRaisesRegex(ValueError, "ambiguous JBeam part definition 'shared'"):
                build_part_catalog([first, second], cache)

    def test_multi_slot_type_survives_disk_backed_catalog(self) -> None:
        with tempfile.TemporaryDirectory() as temporary:
            root = Path(temporary)
            vehicle = root / "vehicles" / "car"
            vehicle.mkdir(parents=True)
            slot_types = ["car_engine_small", "car_engine_large"]
            (vehicle / "engine.jbeam").write_text(json.dumps({
                "shared_engine": {"slotType": slot_types},
            }))
            cache = JBeamDocumentCache(root)
            catalog, failures = build_part_catalog([vehicle], cache)
            self.assertEqual(failures, [])
            self.assertEqual(catalog["shared_engine"]["slotType"], slot_types)

    def test_dependency_sources_keep_their_own_portable_root(self) -> None:
        with tempfile.TemporaryDirectory() as temporary:
            workspace = Path(temporary)
            source = workspace / "mod"
            vehicle = source / "vehicles" / "car"
            dependency = workspace / "beamng-common"
            common = dependency / "vehicles" / "common"
            vehicle.mkdir(parents=True)
            common.mkdir(parents=True)
            (vehicle / "car.jbeam").write_text(json.dumps({
                "car": {"slotType": "main", "slots": [["type:", "default"], ["horn", "horn_stock"]]}
            }))
            (common / "horn.jbeam").write_text(json.dumps({"horn_stock": {"slotType": "horn"}}))
            configuration = vehicle / "stock.pc"
            configuration.write_text(json.dumps({"format": 2, "model": "car", "parts": {}}))

            cache = JBeamDocumentCache(source, [dependency])
            catalog, _ = build_part_catalog([vehicle, common], cache)
            graph = resolve_part_closure(catalog, {})
            index = build_selected_part_index("car", configuration, graph, cache, catalog)

            horn = next(row for row in index["parts"] if row["name"] == "horn_stock")
            self.assertEqual(horn["sourceRoot"], "dependency:0")
            self.assertEqual(horn["source"], "vehicles/common/horn.jbeam")
            self.assertIn({
                "root": "dependency:0",
                "path": "vehicles/common/horn.jbeam",
                "sha256": cache.receipt(common / "horn.jbeam")["sha256"],
                "sizeBytes": (common / "horn.jbeam").stat().st_size,
            }, index["sources"])

    def test_discovery_and_failed_parse_are_charged_before_decode(self) -> None:
        with tempfile.TemporaryDirectory() as temporary:
            root = Path(temporary)
            corpus = root / "vehicles" / "car"
            corpus.mkdir(parents=True)
            malformed = corpus / "bad.jbeam"
            malformed.write_text('{"bad":')
            cache = JBeamDocumentCache(root)
            with self.assertRaises(beamng_jbeam.JBeamParseError):
                cache.load(malformed)
            receipt = cache.receipt(malformed)
            self.assertEqual(cache.total_bytes, malformed.stat().st_size)
            self.assertEqual(receipt["sizeBytes"], malformed.stat().st_size)
            with self.assertRaises(beamng_jbeam.JBeamParseError):
                cache.load(malformed)
            self.assertEqual(cache.parse_counts[malformed.resolve()], 1)

            (corpus / "other.txt").write_text("x")
            with patch.object(beamng_jbeam, "MAX_JBEAM_ENTRIES", 1):
                with self.assertRaisesRegex(ValueError, "discovery exceeds 1 entries"):
                    build_part_catalog([corpus], JBeamDocumentCache(root))

    def test_key_multimap_width_fails_before_wide_pending_allocation(self) -> None:
        module = load_lowerer()
        with self.assertRaisesRegex(ValueError, "traversal cap 8"):
            module.key_multimap([("wide", {str(index): index for index in range(10_000)})], max_entries=8)

    def test_panel_rules_derive_hinges_and_transitive_visual_custody(self) -> None:
        module = load_lowerer()
        cases = [
            ("doorFL", "car_door_FL", [[1, 2, 3], [1, 2, 4]], [0, 1, 0]),
            ("doorFR", "car_door_FR", [[-1, 2, 3], [-1, 2, 4]], [0, 1, 0]),
            ("doorRL", "car_door_RL", [[1, -2, 3], [1, -2, 4]], [0, 1, 0]),
            ("doorRR", "car_door_RR", [[-1, -2, 3], [-1, -2, 4]], [0, 1, 0]),
            ("hood", "car_hood", [[-1, -2, 3], [1, -2, 3]], [1, 0, 0]),
            ("trunk", "car_trunk_sedan", [[0, 1, 2], [0, 3, 2]], [0, 0, -1]),
        ]
        selected = []
        slot_rows = []
        for case_index, (panel_id, slot_type, points, _axis) in enumerate(cases):
            root = f"root_{panel_id}"
            child = f"child_{panel_id}"
            grandchild = f"grandchild_{panel_id}"
            root_body = {
                "slotType": slot_type,
                "nodes": [["id", "posX", "posY", "posZ"],
                          ["a", *points[0]], ["b", *points[1]]],
                "beams": [["id1:", "id2:", "breakGroup"],
                          ["a", "frame_a", f"{panel_id}hinge_a"],
                          ["b", "frame_b", f"{panel_id}hinge_b"]],
                "flexbodies": [["mesh", "[group]:"], [f"mesh_{panel_id}", [slot_type]]],
            }
            selected.extend([
                (slot_type, root, root_body, Path(f"{root}.jbeam")),
                (f"attachment_{case_index}_child", child,
                 {"slotType": f"attachment_{case_index}_child", "flexbodies": [["mesh", "[group]:"],
                                                                [f"mesh_{child}", [slot_type]]]},
                 Path(f"{child}.jbeam")),
                (f"attachment_{case_index}_grandchild", grandchild,
                 {"slotType": f"attachment_{case_index}_grandchild", "flexbodies": [["mesh", "[group]:"],
                                                                      [f"mesh_{grandchild}", [slot_type]]]},
                 Path(f"{grandchild}.jbeam")),
            ])
            slot_rows.extend([
                {"hostPart": root, "selectedPart": child, "resolution": "resolved"},
                {"hostPart": child, "selectedPart": grandchild, "resolution": "resolved"},
            ])
        selected.append(("unrelated", "unrelated", {
            "slotType": "unrelated", "flexbodies": [["mesh", "[group]:"], ["mesh_unrelated", []]],
        }, Path("unrelated.jbeam")))

        panels, evidence = module.articulation_candidates(selected, slot_rows)

        self.assertEqual([panel["id"] for panel in panels], [case[0] for case in cases])
        by_id = {panel["id"]: panel for panel in panels}
        evidence_by_id = {row["panel"]["id"]: row for row in evidence}
        for panel_id, _slot_type, _points, axis in cases:
            panel = by_id[panel_id]
            self.assertEqual(panel["hinge"]["axis"], axis)
            self.assertGreater(math.hypot(*panel["hinge"]["pivot"]), 0)
            self.assertEqual(panel["nodes"], sorted([f"mesh_child_{panel_id}", f"mesh_grandchild_{panel_id}",
                                                     f"mesh_{panel_id}"]))
            self.assertNotIn("mesh_unrelated", panel["nodes"])
            self.assertEqual(panel["fidelity"]["detachable"], [])
            self.assertEqual(evidence_by_id[panel_id]["descendantParts"],
                             [f"child_{panel_id}", f"grandchild_{panel_id}"])

    def test_panel_hinge_derivation_fails_closed_on_weak_evidence(self) -> None:
        module = load_lowerer()
        cases = {
            "no hinge break group": {
                "nodes": [["id", "posX", "posY", "posZ"], ["a", 1, 2, 3], ["b", 1, 2, 4]],
                "beams": [["id1:", "id2:", "breakGroup"], ["a", "frame", "support"]],
            },
            "one panel-local hinge node": {
                "nodes": [["id", "posX", "posY", "posZ"], ["a", 1, 2, 3]],
                "beams": [["id1:", "id2:", "breakGroup"], ["a", "frame", "doorhinge"]],
            },
            "coincident hinge nodes": {
                "nodes": [["id", "posX", "posY", "posZ"], ["a", 1, 2, 3], ["b", 1, 2, 3]],
                "beams": [["id1:", "id2:", "breakGroup"],
                          ["a", "frame_a", "doorhinge"], ["b", "frame_b", "doorhinge"]],
            },
            "origin hinge midpoint": {
                "nodes": [["id", "posX", "posY", "posZ"], ["a", -1, 0, 0], ["b", 1, 0, 0]],
                "beams": [["id1:", "id2:", "breakGroup"],
                          ["a", "frame_a", "hoodhinge"], ["b", "frame_b", "hoodhinge"]],
            },
        }
        for name, body in cases.items():
            with self.subTest(name=name):
                self.assertIsNone(module.source_hinge(body))

    def test_panel_custody_conflicts_and_ambiguous_roots_disable_physics(self) -> None:
        module = load_lowerer()

        def body(slot_type: str, mesh: str, offset: float = 0) -> dict:
            return {"slotType": slot_type,
                    "nodes": [["id", "posX", "posY", "posZ"],
                              ["a", 1 + offset, 2, 3], ["b", 1 + offset, 2, 4]],
                    "beams": [["id1:", "id2:", "breakGroup"],
                              ["a", "frame_a", "hinge"], ["b", "frame_b", "hinge"]],
                    "flexbodies": [["mesh", "[group]:"], [mesh, [slot_type]]]}

        conflicts = [("doorFL", "left", body("car_door_FL", "shared"), Path("left.jbeam")),
                     ("doorFR", "right", body("car_door_FR", "shared", 2), Path("right.jbeam"))]
        panels, _ = module.articulation_candidates(conflicts, [])
        self.assertEqual(panels, [])

        ambiguous = [("doorFL", "first", body("car_door_FL", "first"), Path("first.jbeam")),
                     ("doorFL", "second", body("other_door_FL", "second", 2), Path("second.jbeam"))]
        panels, _ = module.articulation_candidates(ambiguous, [])
        self.assertEqual(panels, [])

    def test_normalizer_repairs_observed_forms_in_one_bounded_pass(self) -> None:
        normalized, diagnostics = normalize_jbeam(
            '{/* header\nline */"rows":[,"a" "b",,00,],// tail\n}')
        self.assertEqual(json.loads(normalized), {"rows": ["a", "b", 0]})
        self.assertEqual(diagnostics, {"leadingZeroValues": 1})
        with patch.object(beamng_jbeam, "MAX_JBEAM_NORMALIZED_CHARS", 8):
            with self.assertRaisesRegex(ValueError, "normalized JBeam exceeds 8"):
                normalize_jbeam('{"expanded":"value"}')

    def test_growing_source_is_stopped_at_the_read_budget(self) -> None:
        with tempfile.TemporaryDirectory() as temporary:
            root = Path(temporary)
            source = root / "exact.jbeam"
            source.write_text('{"part":{}}')
            initial_size = source.stat().st_size
            original_read = beamng_jbeam.os.read
            grew = False

            def grow_then_read(descriptor: int, size: int) -> bytes:
                nonlocal grew
                if not grew:
                    with source.open("ab") as writer:
                        writer.write(b" ")
                    grew = True
                return original_read(descriptor, size)

            with patch.object(beamng_jbeam, "MAX_JBEAM_FILE_BYTES", initial_size), \
                    patch.object(beamng_jbeam.os, "read", side_effect=grow_then_read):
                cache = JBeamDocumentCache(root)
                with self.assertRaisesRegex(ValueError, "exceeds .* while reading"):
                    cache.load(source)
                self.assertEqual(cache.total_bytes, initial_size + 1)

    def test_index_writer_fails_atomically_at_the_consumer_limit(self) -> None:
        with tempfile.TemporaryDirectory() as temporary:
            target = Path(temporary) / "selected.json"
            target.write_text("retained")
            index = {"schemaVersion": beamng_jbeam.SELECTED_PART_INDEX_SCHEMA,
                     "parts": [{"body": "x" * 100}]}
            with patch.object(beamng_jbeam, "MAX_SELECTED_PART_INDEX_BYTES", 32):
                with self.assertRaisesRegex(ValueError, "selected-part index exceeds 32"):
                    write_bound_selected_part_index(index, target, "plan", "a" * 64, None)
            self.assertEqual(target.read_text(), "retained")
            self.assertEqual(list(target.parent.glob(".selected.json.*.tmp")), [])

    def test_catalog_spills_corpus_bodies_and_keeps_rss_sublinear(self) -> None:
        with tempfile.TemporaryDirectory() as temporary:
            root = Path(temporary)
            corpus = root / "vehicles" / "stress"
            corpus.mkdir(parents=True)
            script = """
import json, resource, sys
from pathlib import Path
from beamng_jbeam import JBeamDocumentCache, build_part_catalog
root = Path(sys.argv[1])
cache = JBeamDocumentCache(root)
catalog, failures = build_part_catalog([root / 'vehicles' / 'stress'], cache)
rss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
if sys.platform == 'darwin':
    rss //= 1024
print(json.dumps({'parts': len(catalog), 'documents': len(cache._documents),
                  'spillBytes': catalog.spill_bytes, 'rssKiB': rss,
                  'maxParses': max(cache.parse_counts.values())}))
"""
            payload = "x" * (512 * 1024)
            for index in range(192):
                (corpus / f"part-{index:04d}.jbeam").write_text(json.dumps({
                    f"part_{index:04d}": {"slotType": f"slot_{index:04d}", "payload": payload}
                }))
            result = subprocess.run(
                [sys.executable, "-c", script, str(root)], capture_output=True, text=True,
                env={**os.environ, "PYTHONPATH": str(Path(__file__).resolve().parent)}, check=True)
            metrics = json.loads(result.stdout)
            self.assertEqual(metrics["parts"], 192)
            self.assertEqual(metrics["documents"], 0)
            self.assertEqual(metrics["maxParses"], 1)
            self.assertGreater(metrics["spillBytes"], 90 * 1024 * 1024)
            self.assertLess(metrics["rssKiB"], 160 * 1024)

    def test_extension_scanner_and_decoder_enforce_independent_caps(self) -> None:
        with tempfile.TemporaryDirectory() as temporary:
            root = Path(temporary)
            (root / "a.pc").write_text('{"format":2,"parts":{}}')
            (root / "b.pc").write_text('{"format":2,"parts":{}}')
            (root / "large.jbeam").write_text('{"part":{"payload":"' + "x" * 128 + '"}}')
            with self.assertRaisesRegex(ValueError, r"\.pc asset count exceeds 1"):
                bounded_asset_paths([root], {".pc": (1, 1024, 1024)}, recursive=False)
            with self.assertRaisesRegex(ValueError, r"\.jbeam asset bytes exceed 32"):
                bounded_asset_paths([root], {".jbeam": (4, 32, 1024)}, recursive=False)

            cache = JBeamDocumentCache(root)
            cache.load(root / "a.pc")
            with patch.object(beamng_jbeam, "MAX_PC_SOURCES", 1):
                with self.assertRaisesRegex(ValueError, r"\.pc source count exceeds 1"):
                    cache.load(root / "b.pc")


if __name__ == "__main__":
    unittest.main()
