"""Pre-seeded patterns — 20 patterns covering common failure modes.

These seeds bootstrap the pattern library with proven recovery strategies
for common failure types. Each covers a specific error category with
tool-level specialization where appropriate.

Categories covered:
- Timeout (general, database deadlock)
- Rate limiting (exponential backoff)
- Network (general, DNS, SSL, database, email SMTP)
- Auth (credential refresh)
- Not found (path verification)
- Validation (general, JSON parse, code syntax, AI output)
- Permission (escalation)
- Resource (general reduction, file lock, AI context)
- Unknown (server 500, browser crash)
"""

from xyglue.learn.models import Pattern
from xyglue.learn.patterns import PatternLibrary


# ── Seed pattern definitions ─────────────────────────────────────────

SEED_PATTERNS: list[dict] = [
    {
        "name": "timeout_retry",
        "signature": "timeout:",
        "category": "timeout",
        "description": "Retry with extended timeout for general timeout errors",
        "fix_type": "retry",
        "fix_params": {"multiply_timeout": 2},
        "confidence": 0.8,
        "tags": ["timeout", "retry", "general"],
    },
    {
        "name": "rate_limit_backoff",
        "signature": "rate_limit:",
        "category": "rate_limit",
        "description": "Exponential backoff on rate limit — wait 5s, then 10s, then 20s",
        "fix_type": "retry",
        "fix_params": {"delay_ms": 5000, "backoff": "exponential", "max_retries": 3},
        "confidence": 0.85,
        "tags": ["rate_limit", "backoff", "api"],
    },
    {
        "name": "network_retry",
        "signature": "network:",
        "category": "network",
        "description": "Retry on transient network error with short delay",
        "fix_type": "retry",
        "fix_params": {"delay_ms": 2000, "max_retries": 3},
        "confidence": 0.75,
        "tags": ["network", "retry", "transient"],
    },
    {
        "name": "auth_refresh",
        "signature": "auth:",
        "category": "auth",
        "description": "Refresh authentication credentials and retry",
        "fix_type": "modify_params",
        "fix_params": {"refresh_auth": True},
        "confidence": 0.7,
        "tags": ["auth", "credentials", "refresh"],
    },
    {
        "name": "not_found_check",
        "signature": "not_found:",
        "category": "not_found",
        "description": "Verify resource path and retry with corrected URL",
        "fix_type": "modify_params",
        "fix_params": {"verify_path": True},
        "confidence": 0.6,
        "tags": ["not_found", "path", "verification"],
    },
    {
        "name": "validation_fix",
        "signature": "validation:",
        "category": "validation",
        "description": "Re-validate and fix parameter formatting",
        "fix_type": "modify_params",
        "fix_params": {"revalidate": True},
        "confidence": 0.65,
        "tags": ["validation", "params", "formatting"],
    },
    {
        "name": "permission_escalate",
        "signature": "permission:",
        "category": "permission",
        "description": "Escalate permission issue to user for resolution",
        "fix_type": "escalate",
        "fix_params": {},
        "confidence": 0.5,
        "tags": ["permission", "escalate", "user_action"],
    },
    {
        "name": "resource_reduce",
        "signature": "resource:",
        "category": "resource",
        "description": "Reduce resource usage by 50% and retry",
        "fix_type": "retry",
        "fix_params": {"reduce_batch": True, "reduce_factor": 0.5},
        "confidence": 0.7,
        "tags": ["resource", "memory", "reduction"],
    },
    {
        "name": "dns_retry",
        "signature": "network:browser:",
        "category": "network",
        "description": "DNS resolution retry — flush cache and retry with delay",
        "fix_type": "retry",
        "fix_params": {"delay_ms": 3000, "flush_dns": True},
        "confidence": 0.7,
        "tags": ["network", "dns", "browser"],
    },
    {
        "name": "ssl_skip_verify",
        "signature": "network:http:ssl",
        "category": "network",
        "description": "SSL certificate verification failed — skip verify for dev/test",
        "fix_type": "modify_params",
        "fix_params": {"verify_ssl": False},
        "confidence": 0.6,
        "tags": ["network", "ssl", "certificates"],
    },
    {
        "name": "json_parse_retry",
        "signature": "validation:http:",
        "category": "validation",
        "description": "JSON parse error — retry with explicit Accept header",
        "fix_type": "modify_params",
        "fix_params": {"accept": "application/json"},
        "confidence": 0.65,
        "tags": ["validation", "json", "http"],
    },
    {
        "name": "db_connection_retry",
        "signature": "network:database:",
        "category": "network",
        "description": "Database connection lost — reconnect and retry",
        "fix_type": "retry",
        "fix_params": {"delay_ms": 1000, "reconnect": True},
        "confidence": 0.8,
        "tags": ["network", "database", "connection"],
    },
    {
        "name": "db_deadlock_retry",
        "signature": "timeout:database:",
        "category": "timeout",
        "description": "Database deadlock — retry with randomized delay to break cycle",
        "fix_type": "retry",
        "fix_params": {"delay_ms": 500, "randomize": True},
        "confidence": 0.75,
        "tags": ["timeout", "database", "deadlock"],
    },
    {
        "name": "email_smtp_retry",
        "signature": "network:email:",
        "category": "network",
        "description": "SMTP connection failure — wait and retry delivery",
        "fix_type": "retry",
        "fix_params": {"delay_ms": 5000},
        "confidence": 0.7,
        "tags": ["network", "email", "smtp"],
    },
    {
        "name": "file_lock_retry",
        "signature": "resource:files:",
        "category": "resource",
        "description": "File lock contention — wait for lock release and retry",
        "fix_type": "retry",
        "fix_params": {"delay_ms": 1000},
        "confidence": 0.75,
        "tags": ["resource", "files", "lock"],
    },
    {
        "name": "api_500_retry",
        "signature": "unknown:http:",
        "category": "unknown",
        "description": "HTTP 500 server error — retry with backoff",
        "fix_type": "retry",
        "fix_params": {"delay_ms": 3000, "max_retries": 2},
        "confidence": 0.6,
        "tags": ["server_error", "http", "500"],
    },
    {
        "name": "browser_crash_restart",
        "signature": "unknown:browser:",
        "category": "unknown",
        "description": "Browser crashed — restart browser instance and retry",
        "fix_type": "retry",
        "fix_params": {"restart_browser": True},
        "confidence": 0.7,
        "tags": ["browser", "crash", "restart"],
    },
    {
        "name": "code_syntax_fix",
        "signature": "validation:code:",
        "category": "validation",
        "description": "Code syntax error — lint and auto-fix before retry",
        "fix_type": "modify_params",
        "fix_params": {"lint": True},
        "confidence": 0.6,
        "tags": ["validation", "code", "syntax"],
    },
    {
        "name": "ai_context_reduce",
        "signature": "resource:ai:",
        "category": "resource",
        "description": "AI context window exceeded — reduce context and cap tokens",
        "fix_type": "modify_params",
        "fix_params": {"reduce_context": True, "max_tokens": 2048},
        "confidence": 0.7,
        "tags": ["resource", "ai", "context"],
    },
    {
        "name": "ai_hallucination_retry",
        "signature": "validation:ai:",
        "category": "validation",
        "description": "AI output validation failed — retry with stricter prompt and temperature 0",
        "fix_type": "retry",
        "fix_params": {"stricter_prompt": True, "temperature": 0.0},
        "confidence": 0.6,
        "tags": ["validation", "ai", "hallucination"],
    },
]


def _build_seed_pattern(data: dict) -> Pattern:
    """Build a Pattern from a seed data dict."""
    return Pattern(
        name=data["name"],
        signature=data["signature"],
        category=data["category"],
        description=data["description"],
        fix_type=data["fix_type"],
        fix_params=data["fix_params"],
        confidence=data["confidence"],
        is_seeded=True,
        tags=data.get("tags", []),
    )


def get_seed_patterns() -> list[Pattern]:
    """Get all seed patterns as a list (without adding to a library)."""
    patterns: list[Pattern] = []
    for data in SEED_PATTERNS:
        pattern = _build_seed_pattern(data)
        pattern.record_use(True)  # Pre-validated
        patterns.append(pattern)
    return patterns


def seed_patterns(library: PatternLibrary) -> None:
    """Add 20 pre-seeded patterns covering common failure modes.

    Each pattern is pre-validated with one recorded success to establish
    initial confidence. Seeds cover:
    - Timeout: general retry, database deadlock
    - Rate limiting: exponential backoff
    - Network: general, DNS, SSL, database, email
    - Auth: credential refresh
    - Not found: path verification
    - Validation: general, JSON, code syntax, AI output
    - Permission: escalation
    - Resource: general reduction, file lock, AI context
    - Unknown: server 500, browser crash
    """
    for data in SEED_PATTERNS:
        pattern = _build_seed_pattern(data)
        pattern.record_use(True)  # Pre-validated
        library.add(pattern)


def get_seed_count() -> int:
    """Return the number of seed patterns available."""
    return len(SEED_PATTERNS)


def get_seed_categories() -> list[str]:
    """Return unique categories covered by seeds."""
    return sorted(set(d["category"] for d in SEED_PATTERNS))


def get_seeds_by_category(category: str) -> list[dict]:
    """Get seed pattern data for a specific category."""
    return [d for d in SEED_PATTERNS if d["category"] == category]
