from __future__ import annotations

import importlib.util
import json
from pathlib import Path


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


def write_json(path: Path, payload: dict) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")


def test_build_status_reports_blockers_and_next_action(tmp_path: Path) -> None:
    write_json(
        tmp_path / "plugins/1c/metadata/moxel-schema-registry.json",
        {
            "counts": {"rules": 2, "verified_read": 1, "candidate_read": 1, "write_enabled": 0},
            "rules": [
                {"target": "moxel.inline_text_cell.column", "read_status": "verified_read"},
                {"target": "moxel.named_range.left", "read_status": "candidate_read"},
            ],
        },
    )
    write_json(tmp_path / "reports/1c-template-baselines/moxel-schema-registry-verification.json", {"status": "ok", "counts": {}})
    write_json(tmp_path / "reports/1c-template-baselines/moxel-discovery-pipeline.json", {"status": "ok", "steps": []})
    write_json(
        tmp_path / "reports/1c-template-baselines/moxel-next-action.json",
        {
            "status": "ok",
            "action": {
                "id": "named_range_rectangular_area",
                "target": "named_range",
                "manual_action": "Create rectangle.",
                "capture_command_with_pipeline": "python watcher.py --run-pipeline-after",
            },
        },
    )
    write_json(tmp_path / "reports/1c-template-baselines/moxel-next-action-check.json", {"status": "ok", "counts": {}})

    status = status_mod.build_status(tmp_path)

    assert status["status"] == "ok"
    assert status["next_action"]["id"] == "named_range_rectangular_area"
    assert "moxel.named_range.left" in status["registry"]["candidate_read_targets"]
    assert any("candidate_read rules remain" in blocker for blocker in status["blockers"])


def test_resolve_output_path_keeps_absolute_paths(tmp_path: Path) -> None:
    absolute = tmp_path / "out.json"

    assert status_mod.resolve_output_path(tmp_path / "root", str(absolute)) == absolute


def test_resolve_output_path_anchors_relative_paths(tmp_path: Path) -> None:
    root = tmp_path / "root"

    assert status_mod.resolve_output_path(root, "reports/out.json") == root / "reports/out.json"
