from __future__ import annotations

import importlib.util
from pathlib import Path


ROOT = Path(__file__).resolve().parents[2]


def load_script(name: str):
    path = ROOT / "scripts" / name
    spec = importlib.util.spec_from_file_location(path.stem, path)
    assert spec and spec.loader
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


builder = load_script("build_1c_moxel_schema_registry.py")
checker = load_script("check_1c_moxel_schema_registry.py")


def test_build_registry_promotes_complete_high_confidence_rule_to_verified_read() -> None:
    registry = builder.build_registry(
        {
            "rules": [
                {
                    "id": "inline_text_column_from_last_preceding_scalar_plus_one",
                    "target": "moxel.inline_text_cell.column",
                    "expression": "one_based_column = int(last_numeric(preceding_scalars)) + 1",
                    "confidence": "high",
                    "evidence": {"ok": 16, "total": 16},
                },
                {
                    "target": "moxel.named_range.left",
                    "confidence": "medium",
                    "raw_scalar_indexes": [2, 4],
                },
            ]
        },
        ["discovery.json"],
    )

    rules = {rule["target"]: rule for rule in registry["rules"]}
    assert rules["moxel.inline_text_cell.column"]["read_status"] == "verified_read"
    assert rules["moxel.inline_text_cell.column"]["write_status"] == "blocked_until_roundtrip"
    assert rules["moxel.named_range.left"]["read_status"] == "candidate_read"
    assert registry["counts"]["verified_read"] == 1
    assert registry["counts"]["write_enabled"] == 0


def test_build_registry_promotes_named_range_analysis_over_discovery_candidate() -> None:
    registry = builder.build_registry(
        {
            "rules": [
                {
                    "id": "inline_text_column_from_last_preceding_scalar_plus_one",
                    "target": "moxel.inline_text_cell.column",
                    "confidence": "high",
                    "evidence": {"ok": 1, "total": 1},
                },
                {
                    "target": "moxel.named_range.left",
                    "confidence": "medium",
                    "raw_scalar_indexes": [2, 4],
                },
            ]
        },
        ["discovery.json", "named.json"],
        {
            "rules": [
                {
                    "target": "moxel.named_range.left",
                    "confidence": "high",
                    "raw_scalar_indexes": [2],
                    "expression": "one_based = int(raw_scalar) + 1",
                    "evidence": {"samples": 1, "distinct_rectangular_samples": 1},
                }
            ]
        },
    )

    rules = {rule["target"]: rule for rule in registry["rules"]}
    assert rules["moxel.named_range.left"]["raw_scalar_indexes"] == [2]
    assert rules["moxel.named_range.left"]["read_status"] == "verified_read"
    assert rules["moxel.named_range.left"]["write_status"] == "blocked_until_roundtrip"


def test_check_registry_rejects_write_enabled_rules() -> None:
    registry = builder.build_registry(
        {
            "rules": [
                {
                    "id": "inline_text_column_from_last_preceding_scalar_plus_one",
                    "target": "moxel.inline_text_cell.column",
                    "confidence": "high",
                    "evidence": {"ok": 1, "total": 1},
                }
            ]
        },
        ["discovery.json"],
    )
    registry["rules"][0]["write_status"] = "verified_roundtrip"

    report = checker.check_registry(registry)

    assert report["status"] == "failed"
    assert any("write rules must stay disabled" in failure for failure in report["failures"])


def test_check_registry_rejects_inconsistent_counts() -> None:
    registry = builder.build_registry(
        {
            "rules": [
                {
                    "id": "inline_text_column_from_last_preceding_scalar_plus_one",
                    "target": "moxel.inline_text_cell.column",
                    "confidence": "high",
                    "evidence": {"ok": 1, "total": 1},
                }
            ]
        },
        ["discovery.json"],
    )
    registry["counts"]["rules"] = 99

    report = checker.check_registry(registry)

    assert report["status"] == "failed"
    assert "counts.rules must be 1, got 99" in report["failures"]
