"""Helper for Robot Framework automation profile service tests."""

from __future__ import annotations

import os
import sys
from pathlib import Path
from typing import Any

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))

from cleveragents.application.services.automation_profile_service import (
    AutomationProfileService,
)


def _test_resolve_default() -> None:
    """Resolve default global profile."""
    os.environ.pop("CLEVERAGENTS_AUTOMATION_PROFILE", None)
    svc = AutomationProfileService(repo=None)
    profile = svc.resolve_profile()
    assert profile.name == "manual"
    print("resolve-default-ok")


def _test_resolve_env_override() -> None:
    """Env var overrides empty global default."""
    os.environ["CLEVERAGENTS_AUTOMATION_PROFILE"] = "ci"
    try:
        svc = AutomationProfileService(repo=None)
        profile = svc.resolve_profile()
        assert profile.name == "ci"
        print("resolve-env-override-ok")
    finally:
        os.environ.pop("CLEVERAGENTS_AUTOMATION_PROFILE", None)


def _test_precedence() -> None:
    """Verify precedence: plan > action > project > global."""
    svc = AutomationProfileService(repo=None, global_default="manual")
    # Plan takes precedence
    p = svc.resolve_profile(
        plan_profile="full-auto",
        action_profile="auto",
        project_profile="supervised",
    )
    assert p.name == "full-auto"
    # Action next
    p = svc.resolve_profile(
        action_profile="auto",
        project_profile="supervised",
    )
    assert p.name == "auto"
    # Project next
    p = svc.resolve_profile(project_profile="supervised")
    assert p.name == "supervised"
    # Global fallback
    p = svc.resolve_profile()
    assert p.name == "manual"
    print("precedence-ok")


def _test_list_profiles() -> None:
    """List all profiles."""
    svc = AutomationProfileService(repo=None)
    profiles = svc.list_profiles()
    assert len(profiles) >= 8
    names = {p.name for p in profiles}
    assert "manual" in names
    assert "full-auto" in names
    print("list-profiles-ok")


if __name__ == "__main__":
    cmd = sys.argv[1] if len(sys.argv) > 1 else "resolve-default"
    dispatch: dict[str, Any] = {
        "resolve-default": _test_resolve_default,
        "resolve-env-override": _test_resolve_env_override,
        "precedence": _test_precedence,
        "list-profiles": _test_list_profiles,
    }
    fn = dispatch.get(cmd)
    if fn:
        fn()
    else:
        print(f"Unknown command: {cmd}", file=sys.stderr)
        sys.exit(1)
