"""用户活动追踪 API：页面访问 + 行为埋点 + 运营分析"""

import uuid
from datetime import datetime, timedelta

from fastapi import APIRouter, Depends, HTTPException, Query, Request
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession

from app.compat import UTC
from app.core.permissions import get_current_user, require_role, TenantRole
from app.core.tenant_context import tenant_ctx
from app.core.cache import cache
from app.db import get_db
from app.models.interaction import UserActivityLog
from app.services.analytics_service import get_funnel, get_retention, get_session_trend, get_sessions

router = APIRouter(tags=["Analytics"])


class TrackActivityRequest(BaseModel):
    activity_type: str
    target_type: str | None = None
    target_id: str | None = None
    detail: dict | None = None
    session_id: str | None = None
    duration_seconds: int | None = None
    referer: str | None = None


@router.post("/track", status_code=204)
async def track_activity(
    req: TrackActivityRequest,
    request: Request,
    user: dict = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    """记录用户活动（页面访问/搜索/收藏等），fire-and-forget 风格"""
    log = UserActivityLog(
        user_id=uuid.UUID(user["sub"]),
        tenant_id=uuid.UUID(user["tid"]) if user.get("tid") else None,
        activity_type=req.activity_type,
        target_type=req.target_type,
        target_id=req.target_id,
        detail=req.detail,
        ip_address=request.client.host if request.client else None,
        user_agent=(request.headers.get("user-agent") or "")[:500],
        session_id=req.session_id,
        duration_seconds=req.duration_seconds,
    )
    db.add(log)
    await db.commit()


@router.get("/sessions", summary="会话列表")
async def list_sessions(
    db: AsyncSession = Depends(get_db),
    user: dict = Depends(get_current_user),
    days: int = Query(7, ge=1, le=90),
    page: int = Query(1, ge=1),
    page_size: int = Query(30, ge=1, le=100),
):
    """会话列表（按 session_id 聚合，含起止时间/事件数/时长/入口页/出口页）"""
    tid = tenant_ctx.get()
    tid_uuid = uuid.UUID(tid) if tid else None
    return await get_sessions(db, tenant_id=tid_uuid, days=days, page=page, page_size=page_size)


@router.get("/sessions/trend", summary="会话趋势")
async def session_trend(
    db: AsyncSession = Depends(get_db),
    user: dict = Depends(get_current_user),
    days: int = Query(30, ge=7, le=365),
):
    """每日会话趋势（会话数/独立用户/均时长）"""
    tid = tenant_ctx.get()
    tid_uuid = uuid.UUID(tid) if tid else None
    return await get_session_trend(db, tenant_id=tid_uuid, days=days)


@router.get("/funnel", summary="行为漏斗")
async def behavior_funnel(
    db: AsyncSession = Depends(get_db),
    user: dict = Depends(get_current_user),
    days: int = Query(30, ge=7, le=365),
):
    """行为漏斗（page_view→search→view_literature→save_literature→export）"""
    tid = tenant_ctx.get()
    tid_uuid = uuid.UUID(tid) if tid else None
    return await get_funnel(db, tenant_id=tid_uuid, days=days)


@router.get("/retention", summary="留存分析")
async def retention_analysis(
    db: AsyncSession = Depends(get_db),
    user: dict = Depends(get_current_user),
    weeks: int = Query(12, ge=4, le=52),
):
    """用户留存群组分析（周级 cohort）"""
    tid = tenant_ctx.get()
    tid_uuid = uuid.UUID(tid) if tid else None
    return await get_retention(db, tenant_id=tid_uuid, weeks=weeks)
