"""
User Insight Dashboard API
Scan Redis for all active user insights and return them.
"""

import json
import logging
from datetime import datetime
from zoneinfo import ZoneInfo

from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse

from common.cache import redis_cache

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/user-insights", tags=["User Insights"])

INSIGHT_PREFIX = "identity_key_insight:"
HISTORY_PREFIX = "identity_key_history:"


@router.get("/all", summary="Get all user insights from Redis")
async def get_all_insights(request: Request):
    """
    Scan Redis for all identity_key_insight:* keys and return parsed insights.
    Each insight contains the 6-layer UserInsight structure from the chatbot.
    """
    try:
        client = redis_cache.get_client()
        if not client:
            return {"status": "error", "message": "Redis not available", "insights": []}

        # Scan for all insight keys
        insight_keys = []
        async for key in client.scan_iter(match=f"{INSIGHT_PREFIX}*", count=100):
            if isinstance(key, bytes):
                key = key.decode("utf-8")
            insight_keys.append(key)

        if not insight_keys:
            return {"status": "success", "insights": [], "count": 0}

        # Fetch all values
        results = []
        for key in insight_keys:
            try:
                raw = await client.get(key)
                if not raw:
                    continue

                identity_key = key.replace(INSIGHT_PREFIX, "")
                
                # Parse insight JSON
                if isinstance(raw, bytes):
                    raw = raw.decode("utf-8")
                
                insight_data = None
                try:
                    insight_data = json.loads(raw)
                except json.JSONDecodeError:
                    insight_data = {"raw": raw}

                # Get TTL to estimate when it was created
                ttl = await client.ttl(key)

                # Try to get conversation history count
                msg_count = 0
                history_key = f"{HISTORY_PREFIX}{identity_key}"
                try:
                    history_raw = await client.get(history_key)
                    if history_raw:
                        if isinstance(history_raw, bytes):
                            history_raw = history_raw.decode("utf-8")
                        history = json.loads(history_raw)
                        if isinstance(history, list):
                            msg_count = len(history)
                except Exception:
                    pass

                results.append({
                    "identity_key": identity_key,
                    "insight": insight_data,
                    "ttl_seconds": ttl,
                    "message_count": msg_count,
                })
            except Exception as e:
                logger.warning(f"Error processing key {key}: {e}")
                continue

        # Sort by TTL ascending (newest first = highest TTL)
        results.sort(key=lambda x: x.get("ttl_seconds", 0), reverse=True)

        return {
            "status": "success",
            "insights": results,
            "count": len(results),
        }

    except Exception as e:
        logger.error(f"Error in get_all_insights: {e}", exc_info=True)
        return JSONResponse(
            status_code=500,
            content={"status": "error", "message": str(e), "insights": []},
        )


@router.get("/{identity_key}", summary="Get single user insight")
async def get_single_insight(identity_key: str):
    """Get insight for a specific identity key."""
    try:
        client = redis_cache.get_client()
        if not client:
            return {"status": "error", "message": "Redis not available"}

        raw = await client.get(f"{INSIGHT_PREFIX}{identity_key}")
        if not raw:
            return {"status": "not_found", "identity_key": identity_key}

        if isinstance(raw, bytes):
            raw = raw.decode("utf-8")

        try:
            insight = json.loads(raw)
        except json.JSONDecodeError:
            insight = {"raw": raw}

        # Get conversation history
        history = []
        try:
            hist_raw = await client.get(f"{HISTORY_PREFIX}{identity_key}")
            if hist_raw:
                if isinstance(hist_raw, bytes):
                    hist_raw = hist_raw.decode("utf-8")
                history = json.loads(hist_raw)
        except Exception:
            pass

        ttl = await client.ttl(f"{INSIGHT_PREFIX}{identity_key}")

        return {
            "status": "success",
            "identity_key": identity_key,
            "insight": insight,
            "history": history,
            "ttl_seconds": ttl,
        }

    except Exception as e:
        logger.error(f"Error in get_single_insight: {e}", exc_info=True)
        return JSONResponse(
            status_code=500,
            content={"status": "error", "message": str(e)},
        )


@router.delete("/{identity_key}", summary="Delete user insight")
async def delete_insight(identity_key: str):
    """Delete insight for a specific identity key."""
    try:
        client = redis_cache.get_client()
        if not client:
            return {"status": "error", "message": "Redis not available"}

        deleted = await client.delete(f"{INSIGHT_PREFIX}{identity_key}")
        return {"status": "success", "deleted": bool(deleted)}

    except Exception as e:
        return JSONResponse(status_code=500, content={"status": "error", "message": str(e)})
