from __future__ import annotations

import importlib.util
from argparse import Namespace
from pathlib import Path


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


def args(**overrides) -> Namespace:
    values = {
        "probe": str(pipeline.DEFAULT_PROBE),
        "baseline_discovery": str(pipeline.DEFAULT_BASELINE_DISCOVERY),
        "history_matrix": str(pipeline.DEFAULT_HISTORY_MATRIX),
        "property_candidates": str(pipeline.DEFAULT_PROPERTY_CANDIDATES),
        "property_manifest": str(pipeline.DEFAULT_PROPERTY_MANIFEST),
        "capture_live": False,
        "base_id": "upo_test",
        "label": "pipeline",
        "file_name": None,
        "scan_limit": 30,
        "max_cells": 800,
    }
    values.update(overrides)
    return Namespace(**values)


def test_build_commands_orders_discovery_before_registry() -> None:
    commands = pipeline.build_commands(args())
    names = [name for name, _ in commands]

    assert names == [
        "discover_schema",
        "analyze_named_range_rules",
        "analyze_property_experiments",
        "build_registry",
        "check_registry",
        "verify_registry",
        "plan_next_experiments",
        "get_next_action",
        "check_next_action",
        "status",
    ]


def test_build_commands_can_plan_live_capture_first() -> None:
    commands = pipeline.build_commands(args(capture_live=True, file_name="abc"))

    assert commands[0][0] == "capture_live_probe"
    assert "--file-name" in commands[0][1]
    assert "--output-json" in commands[0][1]
    output_index = commands[0][1].index("--output-json") + 1
    assert commands[0][1][output_index] == "reports\\1c-template-probes\\latest-live-probe.json"
