"""Regression helper for issue #1025 (plan correct auto-resolve).

This helper simulates isolated CLI invocations that share
``CLEVERAGENTS_HOME`` but run from different working directories.

It verifies that ``agents plan correct <decision_id>`` can auto-resolve
the active plan (without ``--plan``) after process-global state is reset.
"""

from __future__ import annotations

import os
import tempfile
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock

from typer.testing import CliRunner
from ulid import ULID

from cleveragents.application.container import get_container, reset_container
from cleveragents.cli.commands.plan import app as plan_app
from cleveragents.config.settings import Settings
from cleveragents.domain.models.core.plan import PlanPhase, ProcessingState


def _reset_process_state() -> None:
    """Reset singleton process state to emulate a fresh subprocess."""
    Settings.reset()
    reset_container()


def _seed_active_plan(home_dir: Path) -> str:
    """Create and persist an Execute/COMPLETE plan under ``home_dir`` DB."""
    os.chdir(home_dir)
    _reset_process_state()

    container = get_container()
    lifecycle = container.plan_lifecycle_service()

    action_name = f"local/issue-1025-{ULID()}"
    lifecycle.create_action(
        name=action_name,
        description="Issue #1025 regression action",
        definition_of_done="Do the thing",
        strategy_actor="local/strategy-actor",
        execution_actor="local/execution-actor",
    )
    plan = lifecycle.use_action(action_name=action_name)
    plan.phase = PlanPhase.EXECUTE
    plan.processing_state = ProcessingState.COMPLETE
    lifecycle.save_plan(plan)

    return plan.identity.plan_id


def run_regression() -> int:
    """Run the regression scenario and return process exit status."""
    with tempfile.TemporaryDirectory(prefix="ca_issue_1025_") as tmp:
        root = Path(tmp)
        home_dir = root / "home"
        workspace_dir = root / "workspace"
        home_dir.mkdir(parents=True, exist_ok=True)
        workspace_dir.mkdir(parents=True, exist_ok=True)

        os.environ["CLEVERAGENTS_HOME"] = str(home_dir)
        os.environ["CLEVERAGENTS_AUTO_APPLY_MIGRATIONS"] = "true"
        os.environ["CLEVERAGENTS_TESTING_USE_MOCK_AI"] = "true"
        os.environ.pop("CLEVERAGENTS_DATABASE_URL", None)
        os.environ.pop("CLEVERAGENTS_TEST_DATABASE_URL", None)

        plan_id = _seed_active_plan(home_dir)

        # Simulate a new isolated invocation from a *different* CWD.
        os.chdir(workspace_dir)
        _reset_process_state()

        fake_svc = MagicMock()
        fake_svc.request_correction.return_value = SimpleNamespace(
            correction_id=str(ULID()),
            mode=SimpleNamespace(value="revert"),
            target_decision_id=str(ULID()),
            guidance="regression guidance",
        )
        fake_svc.execute_correction.return_value = SimpleNamespace(
            correction_id=str(ULID()),
            status=SimpleNamespace(value="applied"),
            new_decisions=[],
            reverted_decisions=[],
        )

        runner = CliRunner()
        container = get_container()
        with container.correction_service.override(fake_svc):
            result = runner.invoke(
                plan_app,
                [
                    "correct",
                    str(ULID()),
                    "--mode",
                    "revert",
                    "--guidance",
                    "regression guidance",
                    "--yes",
                ],
            )

        if result.exit_code != 0:
            print(result.output)
            return 1

        request_call = fake_svc.request_correction.call_args
        if request_call is None:
            print("request_correction was not invoked")
            return 1
        resolved_plan_id = request_call.kwargs.get("plan_id")
        if resolved_plan_id != plan_id:
            print(f"Resolved plan mismatch: expected {plan_id}, got {resolved_plan_id}")
            return 1

        print("issue-1025-plan-correct-isolated-resolve-ok")
        return 0


if __name__ == "__main__":
    raise SystemExit(run_regression())
