from __future__ import annotations

import os
import sys
from collections.abc import Callable
from pathlib import Path
from types import SimpleNamespace


def _ensure_src_on_path() -> None:
    repo_root = Path(__file__).resolve().parents[1]
    src_path = repo_root / "src"
    if str(src_path) not in sys.path:
        sys.path.insert(0, str(src_path))


def run_env_defaults() -> None:
    _ensure_src_on_path()
    from cleveragents.config.settings import Settings, get_settings
    from cleveragents.providers.registry import (
        get_provider_registry,
        reset_provider_registry,
    )

    Settings._instance = None  # type: ignore[attr-defined]
    reset_provider_registry()

    settings = get_settings()
    registry = get_provider_registry(settings)
    provider = registry.create_ai_provider()
    assert provider.name == "openai", provider.name
    print(f"registry-openai-ok {provider.model_id}")


def run_cli_override() -> None:
    _ensure_src_on_path()
    from unittest.mock import patch

    from typer.testing import CliRunner

    from cleveragents.cli.main import app, ensure_cli_commands_registered

    class StubPlanService:
        def build_plan(
            self,
            project: object,
            progress_callback: Callable[[int], None] | None = None,
            actor: str | None = None,
        ) -> list[object]:
            if progress_callback:
                progress_callback(100)

            assert actor == "openrouter/anthropic/claude-sonnet", actor

            provider_name: str | None = None
            model_name: str | None = None

            if actor:
                parts = actor.split("/", 1)
                if parts:
                    provider_name = parts[0]
                if len(parts) > 1:
                    model_name = parts[1]

            print(f"actor-selected {actor}")
            if provider_name and model_name:
                print(f"provider-selected {provider_name} {model_name}")
            return []

    class StubProjectService:
        def get_current_project(self):  # type: ignore[no-untyped-def]
            return SimpleNamespace(name="robot-project", id=1)

    class StubContainer:
        def __init__(self) -> None:
            self._plan = StubPlanService()
            self._project = StubProjectService()

        def plan_service(self) -> StubPlanService:
            return self._plan

        def project_service(self) -> StubProjectService:
            return self._project

    runner = CliRunner()
    stub_container = StubContainer()
    env = {
        "OPENROUTER_API_KEY": os.environ.get(
            "OPENROUTER_API_KEY", "robot-openrouter-key"
        )
    }

    ensure_cli_commands_registered()

    with patch(
        "cleveragents.application.container.get_container", return_value=stub_container
    ):
        result = runner.invoke(
            app,
            [
                "plan",
                "build",
                "--actor",
                "openrouter/anthropic/claude-sonnet",
            ],
            env=env,
            catch_exceptions=False,
        )

    if result.exception:
        raise result.exception
    if result.exit_code != 0:
        raise SystemExit(result.stdout)
    if "provider-selected openrouter anthropic/claude-sonnet" not in result.stdout:
        raise AssertionError("Missing provider log line")

    print("cli-actor-selection-ok")


def main() -> None:
    commands: dict[str, Callable[[], None]] = {
        "env-defaults": run_env_defaults,
        "cli-override": run_cli_override,
    }
    if len(sys.argv) < 2 or sys.argv[1] not in commands:
        raise SystemExit(
            "Usage: helper_provider_registry.py [env-defaults|cli-override]"
        )
    commands[sys.argv[1]]()


if __name__ == "__main__":
    main()
