# @File: backend/routers/whatsapp_analytics.py
# @Desc: Client-side REST endpoints for WhatsApp campaign analytics.
#        Mounted under /api/v1/client/whatsapp so the existing
#        auto-registration picks it up. All endpoints require an
#        authenticated user with an active WhatsApp subscription — the
#        service layer raises 404 otherwise.
from __future__ import annotations

import logging
from typing import List, Optional

from core.database import get_db
from dependencies.auth import get_current_user
from fastapi import APIRouter, Depends, Query
from fastapi.responses import PlainTextResponse, Response
from schemas.auth import UserResponse
from schemas.whatsapp_analytics import (
    CompareOut,
    FunnelOut,
    OverviewOut,
    TimeseriesOut,
)
from schemas.whatsapp_insights import InsightsOut
from services.whatsapp import campaign_analytics, insights as campaign_insights
from sqlalchemy.ext.asyncio import AsyncSession

logger = logging.getLogger(__name__)

router = APIRouter(
    prefix="/api/v1/client/whatsapp/campaigns/analytics",
    tags=["WhatsApp Campaign Analytics"],
)


@router.get("/overview", response_model=OverviewOut, summary="Cross-campaign KPIs + trend")
async def overview(
    start: Optional[str] = Query(None),
    end: Optional[str] = Query(None),
    granularity: str = Query("day"),
    db: AsyncSession = Depends(get_db),
    user: UserResponse = Depends(get_current_user),
) -> dict:
    return await campaign_analytics.overview(
        db, user.id, start=start, end=end, granularity=granularity
    )


@router.get(
    "/compare",
    response_model=CompareOut,
    summary="Side-by-side KPI comparison for selected campaigns",
)
async def compare(
    ids: str = Query(..., description="Comma-separated campaign ids, e.g. 1,2,3"),
    db: AsyncSession = Depends(get_db),
    user: UserResponse = Depends(get_current_user),
) -> dict:
    try:
        id_list = [int(p) for p in ids.split(",") if p.strip()]
    except ValueError:
        id_list = []
    return await campaign_analytics.compare(db, user.id, id_list)


@router.get(
    "/insights",
    response_model=InsightsOut,
    summary="AI-powered insights & recommendations for the dashboard",
)
async def insights(
    start: Optional[str] = Query(None),
    end: Optional[str] = Query(None),
    granularity: str = Query("day"),
    db: AsyncSession = Depends(get_db),
    user: UserResponse = Depends(get_current_user),
) -> dict:
    return await campaign_insights.generate_insights(
        db, user.id, start=start, end=end, granularity=granularity
    )


@router.get(
    "/export.csv",
    response_class=PlainTextResponse,
    summary="All-campaigns summary as CSV",
)
async def export_summary(
    db: AsyncSession = Depends(get_db),
    user: UserResponse = Depends(get_current_user),
) -> Response:
    csv_text = await campaign_analytics.summary_csv(db, user.id)
    headers = {
        "Content-Disposition": "attachment; filename=whatsapp_campaigns_summary.csv"
    }
    return Response(
        content=csv_text, media_type="text/csv; charset=utf-8", headers=headers
    )


@router.get(
    "/{campaign_id}/timeseries",
    response_model=TimeseriesOut,
    summary="Hourly/daily/weekly metrics for one campaign",
)
async def timeseries(
    campaign_id: int,
    start: Optional[str] = Query(None),
    end: Optional[str] = Query(None),
    granularity: str = Query("hour"),
    db: AsyncSession = Depends(get_db),
    user: UserResponse = Depends(get_current_user),
) -> dict:
    return await campaign_analytics.timeseries(
        db,
        user.id,
        campaign_id,
        start=start,
        end=end,
        granularity=granularity,
    )


@router.get(
    "/{campaign_id}/funnel",
    response_model=FunnelOut,
    summary="Sent → Delivered → Read → Replied funnel",
)
async def funnel(
    campaign_id: int,
    db: AsyncSession = Depends(get_db),
    user: UserResponse = Depends(get_current_user),
) -> dict:
    return await campaign_analytics.funnel(db, user.id, campaign_id)


@router.get(
    "/{campaign_id}/export.csv",
    response_class=PlainTextResponse,
    summary="Per-recipient detail CSV for one campaign",
)
async def export_recipients(
    campaign_id: int,
    db: AsyncSession = Depends(get_db),
    user: UserResponse = Depends(get_current_user),
) -> Response:
    filename, csv_text = await campaign_analytics.recipients_csv(
        db, user.id, campaign_id
    )
    headers = {"Content-Disposition": f"attachment; filename={filename}"}
    return Response(
        content=csv_text, media_type="text/csv; charset=utf-8", headers=headers
    )