from __future__ import annotations

import importlib.util
from pathlib import Path


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


def registry() -> dict:
    return {
        "schema": "codex_1c_moxel_schema_registry.v1",
        "rules": [
            {
                "id": "inline_text_column_from_last_preceding_scalar_plus_one",
                "target": "moxel.inline_text_cell.column",
                "read_status": "verified_read",
            },
            {
                "id": "named_left",
                "target": "moxel.named_range.left",
                "read_status": "candidate_read",
                "raw_scalar_indexes": [2, 4],
            },
        ],
    }


def probe(column: int = 2) -> dict:
    return {
        "probe": {
            "cells": [
                {"text": "10-2", "one_based": {"row": 10, "column": column}},
            ],
            "named_ranges": [
                {
                    "name": "R7C2_TEST",
                    "kind": "named_cell_or_range",
                    "range": {"one_based": {"left": 4, "right": 4, "top": 8, "bottom": 8}},
                    "raw_scalars": ["1", "3", "3", "7", "3", "7", "00000000-0000-0000-0000-000000000000", "0"],
                }
            ],
        }
    }


def test_verify_registry_accepts_matching_verified_read_probe() -> None:
    report = verify.verify_registry(registry(), [probe()])

    assert report["status"] == "ok"
    inline = next(item for item in report["results"] if item["target"] == "moxel.inline_text_cell.column")
    assert inline["verification_status"] == "ok"
    named = next(item for item in report["results"] if item["target"] == "moxel.named_range.left")
    assert named["verification_status"] == "ok"


def test_verify_registry_fails_when_verified_read_probe_mismatches() -> None:
    report = verify.verify_registry(registry(), [probe(column=99)])

    assert report["status"] == "failed"
    assert report["counts"]["verified_read_failures"] == 1
