"""
Zero-config setup: auto-detects AI providers from environment variables.
Supports multiple providers in a prioritised fallback chain.
"""

from __future__ import annotations

import os
from typing import List

from playwright_healer.config import (
    AIProvider,
    AIProviderConfig,
    HealerConfig,
    HealingStrategy,
    CacheConfig,
    CacheBackend,
)


def _detect_providers() -> List[AIProviderConfig]:
    """
    Scan environment for all known API keys and build a prioritised list.
    This is the key differentiator: *all* discovered providers are chained
    as fallbacks, so a rate-limit or outage never kills your test run.
    """
    providers: List[AIProviderConfig] = []

    # Priority order: fastest/cheapest first
    if key := os.getenv("GROQ_API_KEY"):
        providers.append(
            AIProviderConfig(
                provider=AIProvider.GROQ,
                api_key=key,
                model=os.getenv("GROQ_MODEL", "llama-3.3-70b-versatile"),
            )
        )

    if key := os.getenv("GEMINI_API_KEY"):
        providers.append(
            AIProviderConfig(
                provider=AIProvider.GEMINI,
                api_key=key,
                model=os.getenv("GEMINI_MODEL", "gemini-2.0-flash"),
            )
        )

    if key := os.getenv("OPENAI_API_KEY"):
        providers.append(
            AIProviderConfig(
                provider=AIProvider.OPENAI,
                api_key=key,
                model=os.getenv("OPENAI_MODEL", "gpt-4o-mini"),
                vision_model=os.getenv("OPENAI_VISION_MODEL", "gpt-4o"),
            )
        )

    if key := os.getenv("ANTHROPIC_API_KEY"):
        providers.append(
            AIProviderConfig(
                provider=AIProvider.ANTHROPIC,
                api_key=key,
                model=os.getenv("ANTHROPIC_MODEL", "claude-3-5-haiku-20241022"),
                vision_model=os.getenv("ANTHROPIC_VISION_MODEL", "claude-3-5-sonnet-20241022"),
            )
        )

    if key := os.getenv("DEEPSEEK_API_KEY"):
        providers.append(
            AIProviderConfig(
                provider=AIProvider.DEEPSEEK,
                api_key=key,
                model=os.getenv("DEEPSEEK_MODEL", "deepseek-chat"),
            )
        )

    if url := os.getenv("PH_API_URL"):
        providers.append(
            AIProviderConfig(
                provider=AIProvider.LOCAL,
                api_key=os.getenv("PH_API_KEY", "not-needed"),
                model=os.getenv("PH_MODEL", "qwen2.5:7b"),
                api_url=url,
            )
        )

    return providers


def _strategy_from_env() -> HealingStrategy:
    raw = os.getenv("PH_STRATEGY", "SMART").upper()
    try:
        return HealingStrategy(raw)
    except ValueError:
        return HealingStrategy.SMART


def _cache_from_env() -> CacheConfig:
    backend_raw = os.getenv("PH_CACHE_BACKEND", "FILE").upper()
    backend = CacheBackend(backend_raw) if backend_raw in CacheBackend.__members__ else CacheBackend.FILE
    return CacheConfig(
        backend=backend,
        max_size=int(os.getenv("PH_CACHE_MAX_SIZE", "1000")),
        ttl_hours=float(os.getenv("PH_CACHE_TTL_HOURS", "48")),
        file_path=os.getenv("PH_CACHE_FILE", ".playwright_healer_cache.json"),
        redis_host=os.getenv("PH_REDIS_HOST", "localhost"),
        redis_port=int(os.getenv("PH_REDIS_PORT", "6379")),
        redis_password=os.getenv("PH_REDIS_PASSWORD"),
    )


def auto_config() -> HealerConfig:
    """
    Build a HealerConfig entirely from environment variables.

    Set at least ONE of:
      GROQ_API_KEY, GEMINI_API_KEY, OPENAI_API_KEY,
      ANTHROPIC_API_KEY, DEEPSEEK_API_KEY, PH_API_URL

    All discovered providers are chained as fallbacks automatically.

    Optional env vars:
      PH_STRATEGY          = SMART | HEURISTIC_ONLY | DOM_ONLY | VISUAL_ONLY | FULL | PARALLEL
      PH_QUICK_TIMEOUT_MS  = 500
      PH_ELEMENT_TIMEOUT_MS= 10000
      PH_CACHE_BACKEND     = FILE | MEMORY | REDIS
      PH_CACHE_TTL_HOURS   = 48
      PH_REPORT_DIR        = playwright-healer-reports
      PH_PREFER_ARIA       = true
      PH_SHADOW_DOM        = true
      PH_ADAPTIVE_TTL      = true
      PH_CONSOLE_LOG       = true
    """
    providers = _detect_providers()
    if not providers:
        raise ValueError(
            "playwright-healer: No AI provider configured.\n"
            "Set at least one of: GROQ_API_KEY, GEMINI_API_KEY, OPENAI_API_KEY, "
            "ANTHROPIC_API_KEY, DEEPSEEK_API_KEY, PH_API_URL"
        )

    def _bool(var: str, default: bool = True) -> bool:
        v = os.getenv(var, "").lower()
        if v in ("1", "true", "yes"):
            return True
        if v in ("0", "false", "no"):
            return False
        return default

    return HealerConfig(
        providers=providers,
        strategy=_strategy_from_env(),
        quick_timeout_ms=int(os.getenv("PH_QUICK_TIMEOUT_MS", "500")),
        element_timeout_ms=int(os.getenv("PH_ELEMENT_TIMEOUT_MS", "10000")),
        enable_heuristic=_bool("PH_HEURISTIC", True),
        enable_dom_fuzzy=_bool("PH_DOM_FUZZY", True),
        enable_shadow_dom=_bool("PH_SHADOW_DOM", True),
        enable_iframe=_bool("PH_IFRAME", True),
        prefer_aria=_bool("PH_PREFER_ARIA", True),
        cache=_cache_from_env(),
        report_dir=os.getenv("PH_REPORT_DIR", "playwright-healer-reports"),
        report_html=_bool("PH_REPORT_HTML", True),
        report_json=_bool("PH_REPORT_JSON", True),
        console_logging=_bool("PH_CONSOLE_LOG", True),
        adaptive_ttl=_bool("PH_ADAPTIVE_TTL", True),
    )
