from fastapi import APIRouter
from pydantic import BaseModel, Field
from typing import List, Dict, Any, Optional
from datetime import datetime
import logging

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/api/v2/telemetry", tags=["telemetry"])


class TelemetryEvent(BaseModel):
    event: Optional[str] = None  # Frontend sends 'event' not 'type'
    type: Optional[str] = None  # Support both formats
    properties: Optional[Dict[str, Any]] = {}
    timestamp: Optional[str] = None
    data: Optional[Dict[str, Any]] = Field(default_factory=dict)
    idempotency_key: Optional[str] = None
    client_sdk: Optional[str] = None
    app_version: Optional[str] = None
    consent_source: Optional[str] = None
    trace_id: Optional[str] = None


class TelemetryBatch(BaseModel):
    events: List[Dict[str, Any]]  # Accept any dict structure from frontend


@router.post("/events")
async def post_events(batch: TelemetryBatch):
    """
    Handle telemetry events from frontend.
    Currently just logs them - in production would store/forward to analytics.
    """
    try:
        # Log the events for debugging
        logger.info(f"Received {len(batch.events)} telemetry events")

        for event_data in batch.events:
            event_name = event_data.get("event") or event_data.get("type", "unknown")
            properties = event_data.get("properties", event_data.get("data", {}))
            timestamp = event_data.get("timestamp", datetime.utcnow().isoformat())

            # Log important events
            if "slack_connected" in event_name.lower():
                logger.info(f"Slack connected: {properties}")
            elif "salesforce_connected" in event_name.lower():
                logger.info(f"Salesforce connected: {properties}")
            else:
                logger.debug(f"Telemetry: {event_name} - {properties}")

        return {"ok": True, "count": len(batch.events), "status": "logged"}

    except Exception as e:
        # Don't fail on telemetry errors - it's non-critical
        logger.error(f"Telemetry error: {str(e)}")
        return {"ok": True, "count": 0, "status": "error", "message": str(e)}
