"""Built-in plan templates for common change types.

Templates adjust the default phases, risks, and verification strategy
generated by ``generate_plan``.  The ``default`` template reproduces the
current behaviour; others are lighter or more specialised.
"""

from __future__ import annotations


TEMPLATES: dict[str, dict] = {
    "default": {
        "description": "General-purpose plan (current default)",
        "phases": [
            {"name": "analysis", "tasks": ["Analyze current implementation", "Identify dependencies and risks"]},
            {"name": "implementation", "tasks": ["Implement changes in safe, testable slices"]},
            {"name": "validation", "tasks": ["Run tests and review for regressions"]},
        ],
        "risks": [
            {
                "id": "RISK-001",
                "description": "Regression impact on existing behaviour",
                "severity": "medium",
                "mitigation": "Add targeted regression tests before changing code",
            },
        ],
        "test_strategy": [
            {"area": "Existing functionality in scope paths", "validation": "Confirm no unintended behaviour changes"},
        ],
    },
    "docs-only": {
        "description": "Documentation-only changes (lighter plan)",
        "phases": [
            {"name": "implementation", "tasks": ["Write or update documentation"]},
            {"name": "validation", "tasks": ["Review for accuracy and completeness"]},
        ],
        "risks": [
            {
                "id": "RISK-001",
                "description": "Documentation drift from actual implementation",
                "severity": "low",
                "mitigation": "Cross-reference code while writing",
            },
        ],
        "test_strategy": [
            {"area": "Documentation accuracy", "validation": "Confirm docs match current code behaviour"},
        ],
    },
    "refactor": {
        "description": "Code refactoring with emphasis on regression safety",
        "phases": [
            {"name": "analysis", "tasks": ["Map existing behaviour and callers", "Write characterization tests"]},
            {"name": "implementation", "tasks": ["Refactor in safe steps, re-running tests after each"]},
            {"name": "validation", "tasks": ["Run full test suite", "Compare before/after behaviour"]},
        ],
        "risks": [
            {
                "id": "RISK-001",
                "description": "Behavioural regression from structural changes",
                "severity": "high",
                "mitigation": "Write characterization tests before refactoring",
            },
            {
                "id": "RISK-002",
                "description": "Downstream callers break due to interface changes",
                "severity": "medium",
                "mitigation": "Audit all call sites before changing signatures",
            },
        ],
        "test_strategy": [
            {"area": "All refactored modules", "validation": "100% existing tests pass, no behaviour changes"},
        ],
    },
    "schema-change": {
        "description": "Database or schema migration with rollback focus",
        "phases": [
            {"name": "analysis", "tasks": ["Document current schema", "Plan migration steps and rollback"]},
            {"name": "implementation", "tasks": ["Write migration", "Write rollback migration", "Update ORM models"]},
            {"name": "validation", "tasks": ["Test migration forward and backward", "Verify data integrity"]},
        ],
        "risks": [
            {
                "id": "RISK-001",
                "description": "Data loss during migration",
                "severity": "critical",
                "mitigation": "Back up data before migration; test on staging first",
            },
            {
                "id": "RISK-002",
                "description": "Rollback migration fails or loses data",
                "severity": "high",
                "mitigation": "Write and test explicit rollback migration",
            },
        ],
        "test_strategy": [
            {"area": "Migration forward", "validation": "Schema matches expected state after migration"},
            {"area": "Migration rollback", "validation": "Schema returns to prior state after rollback"},
        ],
        "rollback_strategy": "Run rollback migration; restore from backup if migration is irreversible",
    },
    "service-integration": {
        "description": "Integrating with an external service or API",
        "phases": [
            {"name": "analysis", "tasks": ["Review service API docs", "Identify auth and rate-limit requirements"]},
            {"name": "implementation", "tasks": ["Implement client/adapter", "Add health check", "Handle errors and retries"]},
            {"name": "validation", "tasks": ["Test against sandbox/staging", "Verify error handling and timeouts"]},
        ],
        "risks": [
            {
                "id": "RISK-001",
                "description": "External service unavailability",
                "severity": "high",
                "mitigation": "Implement circuit breaker and graceful degradation",
            },
            {
                "id": "RISK-002",
                "description": "Rate limiting or quota exhaustion",
                "severity": "medium",
                "mitigation": "Add rate-limit handling and backoff",
            },
        ],
        "test_strategy": [
            {"area": "Service client", "validation": "Integration tests against sandbox environment"},
            {"area": "Error paths", "validation": "Verify timeout, retry, and circuit-breaker behaviour"},
        ],
    },
}


def get_template(name: str) -> dict:
    """Return a plan template by name. Raises KeyError for unknown templates."""
    if name not in TEMPLATES:
        available = ", ".join(sorted(TEMPLATES))
        raise KeyError(f"Unknown template '{name}'. Available: {available}")
    return TEMPLATES[name]


def list_templates() -> list[dict]:
    """Return template names and descriptions."""
    return [
        {"name": name, "description": t["description"]}
        for name, t in TEMPLATES.items()
    ]
