"""Demo data generator for sre-beacon."""

from __future__ import annotations

import os

import yaml


def create_demo_data(base_dir: str) -> dict:
    """Create a suite of demo YAML files for all sre-beacon commands.

    Returns a dict mapping command names to their generated file paths.
    """
    os.makedirs(base_dir, exist_ok=True)
    paths = {}

    paths["slos"] = _write(os.path.join(base_dir, "slos.yaml"), _SLO_DATA)
    paths["actuals"] = _write(os.path.join(base_dir, "actuals.yaml"), _ACTUALS_DATA)
    paths["availability"] = _write(os.path.join(base_dir, "availability.yaml"), _AVAILABILITY_DATA)
    paths["incidents"] = _write(os.path.join(base_dir, "incidents.yaml"), _INCIDENTS_DATA)
    paths["toil"] = _write(os.path.join(base_dir, "toil.yaml"), _TOIL_DATA)
    paths["alerts"] = _write(os.path.join(base_dir, "alert-rules.yaml"), _ALERTS_DATA)
    paths["maturity"] = _write(os.path.join(base_dir, "maturity.yaml"), _MATURITY_DATA)

    return paths


def _write(path: str, data: dict) -> str:
    with open(path, "w", encoding="utf-8") as fh:
        yaml.dump(data, fh, default_flow_style=False, sort_keys=False)
    return path


# ---------------------------------------------------------------------------
# Demo data
# ---------------------------------------------------------------------------

_SLO_DATA = {
    "slos": [
        {
            "name": "API Availability",
            "service": "api-gateway",
            "sli_type": "availability",
            "target": 99.9,
            "window_days": 30,
            "description": "API gateway must be available 99.9% of the time",
        },
        {
            "name": "Checkout Latency P99",
            "service": "checkout-service",
            "sli_type": "latency",
            "target": 99.0,
            "window_days": 30,
            "description": "99% of checkout requests under 500ms",
        },
        {
            "name": "Payment Error Rate",
            "service": "payment-service",
            "sli_type": "error_rate",
            "target": 99.5,
            "window_days": 30,
            "description": "Payment error rate must stay below 0.5%",
        },
        {
            "name": "Search Availability",
            "service": "search-service",
            "sli_type": "availability",
            "target": 99.95,
            "window_days": 30,
            "description": "Search service high availability",
        },
        {
            "name": "Auth Service Uptime",
            "service": "auth-service",
            "sli_type": "availability",
            "target": 99.99,
            "window_days": 30,
            "description": "Authentication must be near-perfect",
        },
    ]
}


_ACTUALS_DATA = {
    "actuals": [
        {"name": "API Availability",      "value": 99.85,  "burn_rate": 1.5},
        {"name": "Checkout Latency P99",   "value": 98.2,   "burn_rate": 2.1},
        {"name": "Payment Error Rate",     "value": 0.3,    "burn_rate": 0.6},
        {"name": "Search Availability",    "value": 99.97,  "burn_rate": 0.4},
        {"name": "Auth Service Uptime",    "value": 99.995, "burn_rate": 0.2},
    ]
}


_AVAILABILITY_DATA = {
    "services": [
        {
            "name": "api-gateway",
            "total_minutes": 43200,
            "downtime_minutes": 45,
            "period": "30 days",
        },
        {
            "name": "database-primary",
            "total_minutes": 43200,
            "downtime_minutes": 5,
            "period": "30 days",
        },
        {
            "name": "cache-cluster",
            "total_minutes": 43200,
            "downtime_minutes": 120,
            "period": "30 days",
        },
        {
            "name": "message-queue",
            "total_minutes": 43200,
            "downtime_minutes": 0,
            "period": "30 days",
        },
    ]
}


_INCIDENTS_DATA = {
    "incidents": [
        {
            "id": "INC-001",
            "title": "API gateway outage — connection pool exhaustion",
            "severity": "P1",
            "service": "api-gateway",
            "detected_at": "2025-01-05T02:30:00",
            "acknowledged_at": "2025-01-05T02:35:00",
            "resolved_at": "2025-01-05T03:15:00",
            "root_cause": "Connection pool leak after deployment",
            "action_items": ["Add connection pool monitoring", "Implement circuit breaker"],
        },
        {
            "id": "INC-002",
            "title": "Payment service high error rate",
            "severity": "P1",
            "service": "payment-service",
            "detected_at": "2025-01-12T14:00:00",
            "acknowledged_at": "2025-01-12T14:10:00",
            "resolved_at": "2025-01-12T15:30:00",
            "root_cause": "Upstream payment provider degradation",
            "action_items": ["Add provider health check", "Implement fallback provider"],
        },
        {
            "id": "INC-003",
            "title": "Search service slow queries",
            "severity": "P2",
            "service": "search-service",
            "detected_at": "2025-01-18T09:00:00",
            "acknowledged_at": "2025-01-18T09:20:00",
            "resolved_at": "2025-01-18T10:00:00",
            "root_cause": "Missing index on new field",
            "action_items": ["Add index migration to CI"],
        },
        {
            "id": "INC-004",
            "title": "Cache eviction storm",
            "severity": "P2",
            "service": "cache-cluster",
            "detected_at": "2025-01-22T16:45:00",
            "acknowledged_at": "2025-01-22T17:00:00",
            "resolved_at": "2025-01-22T18:30:00",
            "root_cause": "Thundering herd after cache node restart",
            "action_items": ["Implement cache warming", "Add jitter to TTLs"],
        },
        {
            "id": "INC-005",
            "title": "Auth service certificate expiry",
            "severity": "P1",
            "service": "auth-service",
            "detected_at": "2025-01-28T00:01:00",
            "acknowledged_at": "2025-01-28T00:15:00",
            "resolved_at": "2025-01-28T00:45:00",
            "root_cause": "TLS certificate not auto-renewed",
            "action_items": ["Automate cert renewal", "Add expiry monitoring"],
        },
        {
            "id": "INC-006",
            "title": "Database replication lag",
            "severity": "P3",
            "service": "database-primary",
            "detected_at": "2025-02-02T11:00:00",
            "acknowledged_at": "2025-02-02T11:30:00",
            "resolved_at": "2025-02-02T12:00:00",
            "root_cause": "Large batch job without throttling",
            "action_items": [],
        },
        {
            "id": "INC-007",
            "title": "Checkout page 500 errors",
            "severity": "P2",
            "service": "checkout-service",
            "detected_at": "2025-02-08T08:00:00",
            "acknowledged_at": "2025-02-08T08:05:00",
            "resolved_at": "2025-02-08T08:30:00",
            "root_cause": "Null pointer in new feature flag path",
            "action_items": ["Add integration tests for feature flag combinations"],
        },
        {
            "id": "INC-008",
            "title": "Message queue consumer lag",
            "severity": "P3",
            "service": "message-queue",
            "detected_at": "2025-02-14T20:00:00",
            "resolved_at": "2025-02-14T21:00:00",
            "root_cause": "Consumer group rebalance during deployment",
            "action_items": [],
        },
    ]
}


_TOIL_DATA = {
    "engineering_hours_per_month": 160,
    "tasks": [
        {
            "name": "Restart stuck pods",
            "frequency": "daily",
            "duration_minutes": 15,
            "automatable": True,
            "category": "kubernetes",
        },
        {
            "name": "Rotate service account keys",
            "frequency": "monthly",
            "duration_minutes": 60,
            "automatable": True,
            "category": "security",
        },
        {
            "name": "Review and close stale alerts",
            "frequency": "daily",
            "duration_minutes": 20,
            "automatable": True,
            "category": "monitoring",
        },
        {
            "name": "Manually scale database replicas",
            "frequency": "weekly",
            "duration_minutes": 30,
            "automatable": True,
            "category": "database",
        },
        {
            "name": "Update SSL certificates",
            "frequency": "quarterly",
            "duration_minutes": 120,
            "automatable": True,
            "category": "security",
        },
        {
            "name": "Respond to capacity alerts",
            "frequency": "weekly",
            "duration_minutes": 45,
            "automatable": False,
            "category": "capacity",
        },
        {
            "name": "Triage error logs",
            "frequency": "daily",
            "duration_minutes": 30,
            "automatable": False,
            "category": "monitoring",
        },
        {
            "name": "Apply OS patches to VMs",
            "frequency": "monthly",
            "duration_minutes": 180,
            "automatable": True,
            "category": "infrastructure",
        },
        {
            "name": "Onboard new services to monitoring",
            "frequency": "weekly",
            "duration_minutes": 60,
            "automatable": True,
            "category": "monitoring",
        },
        {
            "name": "Update Terraform state locks",
            "frequency": "weekly",
            "duration_minutes": 15,
            "automatable": True,
            "category": "infrastructure",
        },
    ]
}


_ALERTS_DATA = {
    "groups": [
        {
            "name": "api-alerts",
            "rules": [
                {
                    "alert": "HighErrorRate",
                    "expr": "rate(http_requests_total{status=~\"5..\"}[5m]) / rate(http_requests_total[5m]) > 0.05",
                    "for": "5m",
                    "labels": {"severity": "critical", "team": "platform"},
                    "annotations": {
                        "summary": "High error rate on {{ $labels.instance }}",
                        "description": "Error rate is above 5% for 5 minutes",
                        "runbook_url": "https://runbooks.example.com/high-error-rate",
                    },
                },
                {
                    "alert": "HighLatency",
                    "expr": "histogram_quantile(0.99, rate(http_request_duration_seconds_bucket[5m])) > 0.5",
                    "for": "10m",
                    "labels": {"severity": "warning"},
                    "annotations": {
                        "summary": "High latency detected",
                    },
                },
                {
                    # Bad: no severity, no for, no annotations
                    "alert": "pod_restarting",
                    "expr": "rate(kube_pod_container_status_restarts_total[15m]) > 0",
                    "labels": {},
                    "annotations": {},
                },
                {
                    # Bad: empty expr
                    "alert": "BrokenAlert",
                    "expr": "",
                    "labels": {"severity": "critical"},
                },
                {
                    # Bad: warning that pages
                    "alert": "DiskSpaceLow",
                    "expr": "node_filesystem_avail_bytes / node_filesystem_size_bytes < 0.1",
                    "for": "15m",
                    "labels": {"severity": "warning", "action": "page"},
                    "annotations": {
                        "summary": "Disk space low on {{ $labels.instance }}",
                        "description": "Less than 10% disk space remaining",
                    },
                },
                {
                    # OK but complex
                    "alert": "MemoryPressure",
                    "expr": "sum(rate(container_memory_working_set_bytes[5m])) by (namespace) / sum(kube_pod_container_resource_limits{resource=\"memory\"}) by (namespace) > 0.9",
                    "for": "5m",
                    "labels": {"severity": "critical", "team": "platform"},
                    "annotations": {
                        "summary": "Memory pressure in {{ $labels.namespace }}",
                        "description": "Memory usage exceeding 90%",
                        "runbook_url": "https://runbooks.example.com/memory-pressure",
                        "dashboard_url": "https://grafana.example.com/d/memory",
                    },
                },
            ],
        },
        {
            "name": "database-alerts",
            "rules": [
                {
                    "alert": "ReplicationLag",
                    "expr": "mysql_slave_seconds_behind_master > 30",
                    "for": "2m",
                    "labels": {"severity": "critical"},
                    "annotations": {
                        "summary": "Database replication lag",
                        "runbook_url": "https://runbooks.example.com/replication-lag",
                    },
                },
                {
                    # Bad: critical with 30m for duration
                    "alert": "ConnectionPoolExhausted",
                    "expr": "pg_stat_activity_count / pg_settings_max_connections > 0.9",
                    "for": "30m",
                    "labels": {"severity": "critical"},
                    "annotations": {
                        "summary": "Connection pool near exhaustion",
                    },
                },
                {
                    # Bad: duplicate name
                    "alert": "HighErrorRate",
                    "expr": "rate(pg_errors_total[5m]) > 10",
                    "for": "5m",
                    "labels": {"severity": "warning"},
                    "annotations": {
                        "summary": "High database error rate",
                    },
                },
            ],
        },
    ]
}


_MATURITY_DATA = {
    "assessment": {
        "slo_adoption": {
            "has_slos": True,
            "slo_count": 5,
            "error_budget_tracking": True,
            "slo_review_cadence": "monthly",
            "stakeholder_visibility": False,
        },
        "incident_management": {
            "has_incident_process": True,
            "has_postmortems": True,
            "action_item_tracking": True,
            "severity_definitions": True,
            "automated_detection": False,
        },
        "monitoring_observability": {
            "has_metrics": True,
            "has_logging": True,
            "has_tracing": False,
            "has_dashboards": True,
            "has_alerting": True,
            "golden_signals": False,
        },
        "toil_reduction": {
            "toil_tracked": True,
            "toil_percentage": 25,
            "automation_projects": True,
            "self_service_tools": False,
        },
        "blameless_culture": {
            "blameless_postmortems": True,
            "learning_reviews": False,
            "psychological_safety": True,
            "knowledge_sharing": True,
        },
        "on_call_practices": {
            "has_rotation": True,
            "rotation_size": 4,
            "compensation": False,
            "runbooks": True,
            "handoff_process": False,
        },
        "capacity_planning": {
            "resource_monitoring": True,
            "growth_projections": False,
            "auto_scaling": True,
            "load_testing": False,
            "cost_optimization": True,
        },
        "change_management": {
            "ci_cd_pipeline": True,
            "canary_deployments": False,
            "rollback_automation": True,
            "feature_flags": False,
            "change_review": True,
        },
    }
}
