from __future__ import annotations

from app.modules.agent.engine.orchestrator.actions.edit_actions import EditActions
from app.modules.agent.engine.orchestrator.execution_context import ExecutionContext
from app.modules.agent.engine.orchestrator.models import (
    ExecutionPlan,
    OutputContract,
    RoutingMeta,
    Scenario,
    TaskConstraints,
    TaskSpec,
)


def _ctx() -> ExecutionContext:
    task = TaskSpec(
        task_id="task-1",
        dialog_session_id="dialog-1",
        rag_session_id="rag-1",
        mode="auto",
        user_message="Добавь в readme.md в конце строку про автора",
        scenario=Scenario.TARGETED_EDIT,
        routing=RoutingMeta(domain_id="project", process_id="edits", confidence=0.95, reason="test"),
        constraints=TaskConstraints(allow_writes=True),
        output_contract=OutputContract(result_type="changeset"),
        metadata={
            "files_map": {
                "README.md": {
                    "path": "README.md",
                    "content": "# Title\n",
                    "content_hash": "hash123",
                }
            }
        },
    )
    plan = ExecutionPlan(
        plan_id="plan-1",
        task_id="task-1",
        scenario=Scenario.TARGETED_EDIT,
        template_id="targeted_edit_v1",
        template_version="1.0",
        steps=[],
    )
    return ExecutionContext(task=task, plan=plan, graph_resolver=lambda *_: None, graph_invoker=lambda *_: {})


def test_edit_actions_resolve_path_case_insensitive_and_keep_update() -> None:
    actions = EditActions()
    ctx = _ctx()

    actions.resolve_target(ctx)
    actions.load_target_context(ctx)
    actions.plan_minimal_patch(ctx)
    actions.generate_patch(ctx)

    target = ctx.artifacts.get_content("target_context", {})
    changeset = ctx.artifacts.get_content("raw_changeset", [])

    assert target["path"] == "README.md"
    assert changeset[0]["path"] == "README.md"
    assert changeset[0]["op"] == "update"
