from __future__ import annotations

import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "scripts"))

import generate_1c_training_data as gen  # noqa: E402


def test_verified_write_records_capture_safe_route() -> None:
    registry = {
        "base_id": "upo_test",
        "table": "ConfigSave",
        "file_name": "form.0",
        "patterns": [
            {
                "effective_section": "items",
                "canonical_property": "title",
                "presentation": "Заголовок",
                "value_type": "string",
                "write_path": "1.2.3",
                "source_kind": "local",
                "verification": "source_aware_readback",
            }
        ],
    }

    records = gen.verified_write_records(registry, "registry-smoke", max_records=5)

    assert len(records) == 1
    record = records[0]
    assert record["id"] == "registry-smoke-verified-write-001"
    assert record["metadata"]["task"] == "metadata-write-verified"
    assistant = record["messages"][-1]["content"]
    assert "base_id: upo_test" in assistant
    assert "apply_and_rollback" in assistant
    assert "Не расширяй allowlist" in assistant


def test_write_learning_plan_records_keep_cases_manual() -> None:
    plan = {
        "workflow": ["capture_before", "capture_after", "diff", "smoke_rule"],
        "cases": [
            {
                "id": "learn-001",
                "action": "run_before_after_learning_for_parameter",
                "property": "параметр 14",
                "value_type": "integer_atom",
                "write_path": "1.22.14",
                "current_value": "2",
                "manual_step": {
                    "target": "ФормаКоманднаяПанель",
                    "instruction": "Измени свойство в тестовой базе",
                },
            }
        ],
    }

    records = gen.write_learning_plan_records(plan, "plan-smoke", max_records=1)

    assert len(records) == 1
    record = records[0]
    assert record["metadata"]["task"] == "metadata-write-learning-plan"
    assistant = record["messages"][-1]["content"]
    assert "Это не готовый allowlist" in assistant
    assert "capture_before" in assistant
    assert "smoke-проверки" in assistant
