from __future__ import annotations

import importlib.util
import json
from pathlib import Path


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


def test_append_manifest_experiment_creates_relative_paths(tmp_path: Path) -> None:
    manifest_path = tmp_path / "experiments.json"
    before = tmp_path / "before.json"
    after = tmp_path / "after.json"
    before.write_text("{}", encoding="utf-8")
    after.write_text("{}", encoding="utf-8")

    experiment = watch.append_manifest_experiment(
        manifest_path,
        property_name="ВертикальноеПоложение",
        operation="manual_one_property_save",
        target_text="Ячейка 7 - 2",
        target_name="R7C2_TEST",
        before_path=before,
        after_path=after,
    )

    manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    assert experiment["before"] == "before.json"
    assert experiment["after"] == "after.json"
    assert manifest["experiments"] == [experiment]


def test_snapshot_identity_uses_stable_change_fields() -> None:
    identity = watch.snapshot_identity({"file_name": "abc", "modified": "4026-01-01", "bytes": 123, "label": "ignored"})

    assert identity == {"file_name": "abc", "modified": "4026-01-01", "bytes": 123}


def test_pipeline_command_uses_after_probe_and_manifest() -> None:
    command = watch.pipeline_command(Path("after.json"), Path("manifest.json"))

    assert command[1:] == [
        "scripts/run_1c_moxel_discovery_pipeline.py",
        "--probe",
        "after.json",
        "--property-manifest",
        "manifest.json",
    ]
