"""Protocol source resolver."""

from pathlib import Path
from typing import Tuple

from rich.console import Console

from cokodo_agent.fetcher.base import FetcherError
from cokodo_agent.fetcher.builtin import BuiltinFetcher

console = Console()


def get_protocol(online: bool = False) -> Tuple[Path, str]:
    """
    Get protocol from available sources.

    Default: use built-in bundled protocol (fast, no network).
    Pass online=True to fetch the latest version from GitHub Release instead.

    Args:
        online: If True, fetch from GitHub Release (requires httpx / [network] extra);
                falls back to built-in if network is unavailable.

    Returns:
        Tuple of (protocol_path, version)

    Raises:
        FetcherError: If all sources fail
    """

    if not online:
        fetcher = BuiltinFetcher()
        return fetcher.fetch()

    # Online mode: try GitHub first, fall back to built-in
    sources = []
    try:
        from cokodo_agent.fetcher.github import GitHubReleaseFetcher
        sources.append(GitHubReleaseFetcher())
    except ImportError:
        console.print(
            "  [yellow]Note:[/yellow] httpx not installed; "
            "install cokodo-agent[network] to enable GitHub fetch."
        )
    sources.append(BuiltinFetcher())

    errors = []

    for i, source in enumerate(sources, 1):
        source_label = f"[{i}/{len(sources)}] {source.name}"

        try:
            console.print(f"  {source_label}...", end=" ")
            path, version = source.fetch()
            console.print(f"[green]OK[/green] (v{version})")
            return path, version

        except FetcherError as e:
            console.print("[yellow]unavailable[/yellow]")
            errors.append(f"{source.name}: {e}")
            continue
        except Exception as e:
            console.print("[red]error[/red]")
            errors.append(f"{source.name}: {e}")
            continue

    error_details = "\n".join(f"  - {err}" for err in errors)
    raise FetcherError(f"All protocol sources failed:\n{error_details}")
