"""
Seed telemetry insight tickets for UI development.

Usage:
    python -m src.fmatch.saas.scripts.seed_insight_tickets
"""

import asyncio
from datetime import timedelta
from uuid import uuid4

from ..db import AsyncSessionLocal
from ..models import InsightTicketSeverity, InsightTicketType, utcnow
from ..repos.telemetry_insight_repo import TelemetryInsightRepo
from ..services.insight_context_sanitizer import sanitize_context


async def seed_insight_tickets() -> None:
    now = utcnow()
    samples = [
        {
            "fingerprint": uuid4().hex,
            "ticket_type": InsightTicketType.ERROR_FIRST_SEEN,
            "severity": InsightTicketSeverity.HIGH,
            "title": "New error: validation_failed in grr_model/build_completed",
            "feature": "grr_model",
            "action": "grr_model_build_completed",
            "error_code": "validation",
            "event_count": 12,
            "affected_orgs": 3,
        },
        {
            "fingerprint": uuid4().hex,
            "ticket_type": InsightTicketType.ERROR_RATE_REGRESSION,
            "severity": InsightTicketSeverity.CRITICAL,
            "title": "Error rate spike: flow_builder/build_completed (1.2% -> 14.5%)",
            "feature": "flow_builder",
            "action": "flow_builder_build_completed",
            "event_count": 28,
            "affected_orgs": 6,
        },
        {
            "fingerprint": uuid4().hex,
            "ticket_type": InsightTicketType.ERROR_FIRST_SEEN,
            "severity": InsightTicketSeverity.MEDIUM,
            "title": "New error: timeout in salesforce_import/build_started",
            "feature": "salesforce_import",
            "action": "salesforce_import_build_started",
            "error_code": "timeout",
            "event_count": 6,
            "affected_orgs": 2,
        },
        {
            "fingerprint": uuid4().hex,
            "ticket_type": InsightTicketType.USAGE_ANOMALY,
            "severity": InsightTicketSeverity.LOW,
            "title": "Usage anomaly: model_intel opened drop-off",
            "feature": "model_intel",
            "action": "model_intel_opened",
            "event_count": 40,
            "affected_orgs": 8,
        },
        {
            "fingerprint": uuid4().hex,
            "ticket_type": InsightTicketType.ERROR_RATE_REGRESSION,
            "severity": InsightTicketSeverity.MEDIUM,
            "title": "Error rate spike: salesforce_query/build_completed (0.8% -> 4.2%)",
            "feature": "salesforce_query",
            "action": "salesforce_query_build_completed",
            "event_count": 9,
            "affected_orgs": 4,
        },
    ]

    async with AsyncSessionLocal() as db:
        repo = TelemetryInsightRepo(db)
        for idx, sample in enumerate(samples):
            context = {
                "type": sample["ticket_type"].value,
                "dimensions": {
                    "feature": sample.get("feature"),
                    "action": sample.get("action"),
                    "error_code": sample.get("error_code"),
                },
                "sample_attrs": [
                    {"source_version": "1.2.3", "duration_ms": 1800},
                    {"source_version": "1.2.3", "duration_ms": 2100},
                ],
            }
            await repo.upsert_ticket(
                fingerprint=sample["fingerprint"],
                ticket_type=sample["ticket_type"],
                severity=sample["severity"],
                title=sample["title"],
                context_json=sanitize_context(context),
                feature=sample.get("feature"),
                action=sample.get("action"),
                error_code=sample.get("error_code"),
                event_count=sample["event_count"],
                affected_orgs=sample["affected_orgs"],
                first_seen_at=now - timedelta(hours=4 + idx),
                last_seen_at=now - timedelta(hours=idx),
            )


def main() -> None:
    asyncio.run(seed_insight_tickets())


if __name__ == "__main__":
    main()
