"""
Admin Analytics API
Revenue, usage, and business metrics for admin dashboard.

Provides:
- MRR (Monthly Recurring Revenue) by tier
- Total active subscriptions
- Credit sales (one-time purchases)
- Usage metrics
- Churn indicators (TODO: when we have subscription cancellation tracking)
"""

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func, case
from typing import Dict, Any
import logging

from ...db import get_session
from ...models import Account, UsageQuotaModel
from ...auth_security import require_admin, AdminContext
from ...services.admin_audit import log_admin_action
from ...middleware.quota_checker import TIER_LIMITS

log = logging.getLogger(__name__)

router = APIRouter(prefix="/admin/analytics", tags=["Admin Analytics"])


@router.get("/revenue")
async def get_revenue_metrics(
    admin_ctx: AdminContext = Depends(require_admin),
    db: AsyncSession = Depends(get_session),
) -> Dict[str, Any]:
    """
    Get revenue metrics for the business.

    Returns:
        - mrr: Monthly Recurring Revenue (total and by tier)
        - arr: Annual Recurring Revenue
        - active_subscriptions: Count by tier
        - credit_purchases: Last 30 days (TODO: when we track purchases)
    """
    try:
        # Get subscription breakdown by tier
        tier_query = (
            select(
                UsageQuotaModel.tier,
                func.count(UsageQuotaModel.account_id).label("count"),
            )
            .where(UsageQuotaModel.tier.isnot(None))
            .group_by(UsageQuotaModel.tier)
        )

        tier_result = await db.execute(tier_query)
        tier_rows = tier_result.all()

        # Calculate MRR by tier
        # Pricing: Pro = $49/mo, Scale = $149/mo, Free = $0
        tier_pricing = {
            "free": 0,
            "pro": 49,
            "scale": 149,
            "business": 149,  # Legacy alias for scale
        }

        mrr_by_tier = []
        total_mrr = 0

        for row in tier_rows:
            tier_name = row.tier or "free"
            count = row.count
            price = tier_pricing.get(tier_name, 0)
            revenue = count * price

            mrr_by_tier.append(
                {
                    "tier": tier_name,
                    "subscribers": count,
                    "price_per_month": price,
                    "revenue": revenue,
                }
            )

            total_mrr += revenue

        # Get total accounts
        total_accounts_result = await db.execute(select(func.count(Account.id)))
        total_accounts = total_accounts_result.scalar() or 0

        # Get accounts with Stripe subscriptions
        paid_accounts_result = await db.execute(
            select(func.count(Account.id)).where(
                Account.stripe_subscription_id.isnot(None)
            )
        )
        paid_accounts = paid_accounts_result.scalar() or 0

        # Calculate metrics
        arr = total_mrr * 12
        free_accounts = total_accounts - paid_accounts

        # Get usage stats
        usage_query = select(
            func.sum(UsageQuotaModel.monthly_rows_used).label("total_rows_used"),
            func.sum(UsageQuotaModel.enrichment_credits_used).label(
                "total_credits_used"
            ),
        )
        usage_result = await db.execute(usage_query)
        usage_row = usage_result.one()

        # Log admin action
        await log_admin_action(
            admin_user_id=admin_ctx.user_id,
            admin_email=admin_ctx.email,
            action="view_revenue_analytics",
            db=db,
        )

        return {
            "ok": True,
            "data": {
                "revenue": {
                    "mrr": total_mrr,
                    "arr": arr,
                    "by_tier": mrr_by_tier,
                },
                "subscriptions": {
                    "total_accounts": total_accounts,
                    "paid_accounts": paid_accounts,
                    "free_accounts": free_accounts,
                    "by_tier": [
                        {"tier": row["tier"], "count": row["subscribers"]}
                        for row in mrr_by_tier
                    ],
                },
                "usage": {
                    "total_rows_matched_this_month": usage_row.total_rows_used or 0,
                    "total_credits_consumed_this_month": usage_row.total_credits_used
                    or 0,
                },
                # TODO: Add credit purchases when we have purchase tracking
                "credit_sales_30d": {
                    "revenue": 0,
                    "count": 0,
                    "note": "TODO: Implement when Stripe credit purchase tracking is added",
                },
            },
        }

    except Exception as e:
        log.error(f"Failed to get revenue metrics: {e}", exc_info=True)
        raise HTTPException(500, f"Failed to get revenue metrics: {e}")


@router.get("/usage")
async def get_usage_metrics(
    admin_ctx: AdminContext = Depends(require_admin),
    db: AsyncSession = Depends(get_session),
) -> Dict[str, Any]:
    """
    Get usage metrics across all customers.

    Returns:
        - total_rows_matched: Current month
        - total_credits_consumed: Current month
        - quota_utilization: % of customers approaching limits
        - top_users: Accounts with highest usage
    """
    try:
        # Get top 10 users by monthly rows usage
        top_users_query = (
            select(
                Account.id,
                Account.name,
                UsageQuotaModel.tier,
                UsageQuotaModel.monthly_rows_used,
                UsageQuotaModel.enrichment_credits_used,
            )
            .select_from(Account)
            .join(UsageQuotaModel, Account.id == UsageQuotaModel.account_id)
            .order_by(UsageQuotaModel.monthly_rows_used.desc())
            .limit(10)
        )

        top_users_result = await db.execute(top_users_query)
        top_users_rows = top_users_result.all()

        top_users = [
            {
                "account_id": row.id,
                "account_name": row.name,
                "tier": row.tier or "free",
                "rows_used": row.monthly_rows_used,
                "credits_used": row.enrichment_credits_used,
            }
            for row in top_users_rows
        ]

        # Get quota utilization stats
        # Calculate how many users are above 75% of their quota
        utilization_query = select(
            UsageQuotaModel.tier,
            func.count(UsageQuotaModel.account_id).label("total"),
            func.sum(
                case(
                    (
                        UsageQuotaModel.monthly_rows_used
                        > (TIER_LIMITS["free"]["monthly_rows"] * 0.75),
                        1,
                    ),
                    else_=0,
                )
            ).label("above_75_pct"),
        ).group_by(UsageQuotaModel.tier)

        utilization_result = await db.execute(utilization_query)
        utilization_rows = utilization_result.all()

        quota_utilization = [
            {
                "tier": row.tier or "free",
                "total_accounts": row.total,
                "accounts_above_75_pct": row.above_75_pct or 0,
                "percentage": (row.above_75_pct or 0) / row.total * 100
                if row.total > 0
                else 0,
            }
            for row in utilization_rows
        ]

        # Log admin action
        await log_admin_action(
            admin_user_id=admin_ctx.user_id,
            admin_email=admin_ctx.email,
            action="view_usage_analytics",
            db=db,
        )

        return {
            "ok": True,
            "data": {
                "top_users": top_users,
                "quota_utilization": quota_utilization,
            },
        }

    except Exception as e:
        log.error(f"Failed to get usage metrics: {e}", exc_info=True)
        raise HTTPException(500, f"Failed to get usage metrics: {e}")
