from __future__ import annotations

import importlib.util
import json
from pathlib import Path


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


def test_analyze_experiment_ranks_target_style_path(tmp_path: Path) -> None:
    before = {
        "structure": {
            "counts": {"cell_style_candidates": 1},
            "cell_style_candidates": [
                {
                    "text": "Ячейка 7 - 2",
                    "tree_position": "$.39",
                    "style_evidence": {"last_7_preceding_values": ["1", "2", "7", "0", "3", "2", "3"]},
                    "next_moxel_record": {"type": "atom", "value": "4", "tree_position": "$.40"},
                }
            ],
        }
    }
    after = {
        "structure": {
            "counts": {"cell_style_candidates": 1},
            "cell_style_candidates": [
                {
                    "text": "Ячейка 7 - 2",
                    "tree_position": "$.39",
                    "style_evidence": {"last_7_preceding_values": ["1", "2", "7", "0", "3", "2", "3"]},
                    "next_moxel_record": {"type": "atom", "value": "5", "tree_position": "$.40"},
                }
            ],
        }
    }
    before_path = tmp_path / "before.json"
    after_path = tmp_path / "after.json"
    before_path.write_text(json.dumps(before, ensure_ascii=False), encoding="utf-8")
    after_path.write_text(json.dumps(after, ensure_ascii=False), encoding="utf-8")

    result = experiments.analyze_experiment(
        {
            "property": "ВертикальноеПоложение",
            "target_text": "Ячейка 7 - 2",
            "before": str(before_path),
            "after": str(after_path),
        },
        tmp_path,
    )

    assert result["confidence"] in {"medium", "high"}
    assert result["candidate_paths"]
    assert "target_cell_styles" in result["candidate_paths"][0]["path"]
    assert result["candidate_paths"][0]["after"] == "5"


def test_default_probe_plan_covers_core_cell_and_layout_properties() -> None:
    properties = {item["property"] for item in experiments.default_probe_plan()}

    assert "ГоризонтальноеПоложение" in properties
    assert "ВертикальноеПоложение" in properties
    assert "ШиринаКолонки" in properties
    assert "Объединение" in properties


def test_resolve_manifest_path_accepts_project_relative_paths() -> None:
    path = experiments.resolve_manifest_path(
        "tests/1c/test_moxel_property_experiments.py",
        ROOT / "reports" / "1c-template-baselines",
    )

    assert path == Path(__file__).resolve()
