from __future__ import annotations

import importlib.util
from pathlib import Path


ROOT = Path(__file__).resolve().parents[2]
SCRIPT = ROOT / "scripts" / "analyze_1c_moxel_named_range_rules.py"
SPEC = importlib.util.spec_from_file_location("analyze_1c_moxel_named_range_rules", SCRIPT)
assert SPEC and SPEC.loader
named_rules = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(named_rules)


def probe(raw_scalars: list[str], one_based: dict[str, int], name: str = "RANGE_RECT_TEST") -> dict:
    return {
        "probe": {
            "named_ranges": [
                {
                    "name": name,
                    "kind": "named_cell_or_range",
                    "range": {"one_based": one_based},
                    "raw_scalars": raw_scalars,
                }
            ]
        }
    }


def test_single_cell_named_range_stays_ambiguous() -> None:
    result = named_rules.analyze(
        [
            probe(
                ["1", "3", "3", "7", "3", "7", "00000000-0000-0000-0000-000000000000", "0"],
                {"left": 4, "right": 4, "top": 8, "bottom": 8},
                name="R7C2_TEST",
            )
        ],
        "R7C2_TEST",
    )
    rules = {rule["target"]: rule for rule in result["rules"]}

    assert rules["moxel.named_range.left"]["confidence"] == "medium"
    assert rules["moxel.named_range.left"]["raw_scalar_indexes"] == [2, 4]
    assert rules["moxel.named_range.top"]["raw_scalar_indexes"] == [3, 5]


def test_rectangular_named_range_promotes_unique_indexes() -> None:
    result = named_rules.analyze(
        [
            probe(
                ["1", "0", "3", "7", "6", "9", "00000000-0000-0000-0000-000000000000", "0"],
                {"left": 4, "top": 8, "right": 7, "bottom": 10},
            )
        ],
        "RANGE_RECT_TEST",
    )
    rules = {rule["target"]: rule for rule in result["rules"]}

    assert rules["moxel.named_range.left"]["confidence"] == "high"
    assert rules["moxel.named_range.left"]["raw_scalar_indexes"] == [2]
    assert rules["moxel.named_range.top"]["raw_scalar_indexes"] == [3]
    assert rules["moxel.named_range.right"]["raw_scalar_indexes"] == [4]
    assert rules["moxel.named_range.bottom"]["raw_scalar_indexes"] == [5]
