from __future__ import annotations

from autodebug.agent.sdk_bridge import (
    _LEGACY_ALIAS_TARGETS,
    get_tool_names,
    populate_registry_from_agent,
)
from autodebug.agent.tools import register_hikaflow_tools


class _FakeAgent:
    def __init__(self):
        self._function_tools = {}

    def tool(self, fn):
        self._function_tools[fn.__name__] = type("Tool", (), {"function": fn})()
        return fn


_COMPACT_EXPECTED = {
    "incident_overview",
    "failure_similarity_search",
    "generate_fix_candidates",
    "validate_fix_candidate",
    "create_fix_pr",
    "quarantine_control",
    "codebase_scan",
    "review_files",
    "run_tests",
    "update_findings",
    "knowledge_memory",
    "project_health_snapshot",
}


def _build_fake() -> _FakeAgent:
    fake = _FakeAgent()
    register_hikaflow_tools(fake)
    return fake


def test_compact_profile_exports_exact_12_tools():
    fake = _build_fake()
    populate_registry_from_agent(fake, profile="compact")
    names = set(get_tool_names(profile="compact"))
    assert names == _COMPACT_EXPECTED


def test_admin_profile_exports_more_than_compact():
    fake = _build_fake()
    populate_registry_from_agent(fake, profile="compact")
    compact = set(get_tool_names(profile="compact"))

    populate_registry_from_agent(fake, profile="admin")
    admin = set(get_tool_names(profile="admin"))

    assert compact == _COMPACT_EXPECTED
    assert len(admin) > len(compact)
    assert "fetch_production_errors" in admin
    assert "incident_overview" in admin


def test_unknown_profile_falls_back_to_compact():
    fake = _build_fake()
    populate_registry_from_agent(fake, profile="unknown-profile")
    names = set(get_tool_names(profile="unknown-profile"))
    assert names == _COMPACT_EXPECTED


def test_legacy_aliases_are_opt_in(monkeypatch):
    fake = _build_fake()
    monkeypatch.setenv("HIKAFLOW_ENABLE_LEGACY_ALIASES", "1")
    populate_registry_from_agent(fake, profile="compact")
    names = set(get_tool_names(profile="compact"))
    assert "fetch_production_errors" in names
    assert "incident_overview" in names
    monkeypatch.delenv("HIKAFLOW_ENABLE_LEGACY_ALIASES", raising=False)


def test_legacy_alias_smoke_suite_all_mappings_exposed(monkeypatch):
    fake = _build_fake()
    monkeypatch.setenv("HIKAFLOW_ENABLE_LEGACY_ALIASES", "1")
    populate_registry_from_agent(fake, profile="compact")
    names = set(get_tool_names(profile="compact"))
    assert set(_LEGACY_ALIAS_TARGETS.keys()).issubset(names)
