# src/fmatch/saas/api/v2/rate_limits.py
"""Rate limits and usage tracking API endpoints."""

from fastapi import APIRouter
from pydantic import BaseModel
from typing import Optional, Dict
from datetime import datetime, date
import random

router = APIRouter(prefix="/api/v2/rate-limits", tags=["rate-limits"])


class RateLimitsUsage(BaseModel):
    team_id: str
    date: str
    records_today: int
    cost_today: float
    limits: Dict[str, int]
    approvals_required: Optional[bool] = False


class RateLimitsConfig(BaseModel):
    daily_records: int = 100000
    daily_cost: float = 100.0
    monthly_records: int = 2000000
    monthly_cost: float = 2000.0
    approval_threshold: float = 80.0  # Percentage


# Mock usage data
def get_mock_usage():
    """Generate mock usage data for demonstration."""
    records = random.randint(5000, 50000)
    cost_per_record = 0.001

    return {
        "team_id": "team_123",
        "date": date.today().isoformat(),
        "records_today": records,
        "cost_today": round(records * cost_per_record, 2),
        "limits": {"records": 100000, "cost": 100},
        "approvals_required": records > 80000,  # Require approval if >80% of limit
    }


@router.get("/usage")
async def get_rate_limits_usage():
    """Get current rate limits usage for the team."""
    return get_mock_usage()


@router.get("/config")
async def get_rate_limits_config():
    """Get rate limits configuration."""
    return RateLimitsConfig()


@router.put("/config")
async def update_rate_limits_config(config: RateLimitsConfig):
    """Update rate limits configuration (admin only)."""
    # In production, check admin permissions
    # For now, just return success
    return {"message": "Rate limits configuration updated", "config": config}


@router.get("/history")
async def get_usage_history(days: int = 7):
    """Get usage history for the past N days."""
    history = []

    for i in range(days):
        day_offset = days - i - 1
        usage_date = date.fromordinal(date.today().toordinal() - day_offset)
        records = random.randint(3000, 60000)

        history.append(
            {
                "date": usage_date.isoformat(),
                "records": records,
                "cost": round(records * 0.001, 2),
                "peak_hour": random.randint(9, 17),
                "peak_records": random.randint(500, 5000),
            }
        )

    return {
        "history": history,
        "total_records": sum(h["records"] for h in history),
        "total_cost": sum(h["cost"] for h in history),
        "average_daily": sum(h["records"] for h in history) // len(history),
    }


@router.post("/approve")
async def approve_over_limit(reason: str):
    """Approve processing when over rate limits."""
    return {
        "approved": True,
        "approval_id": f"appr_{datetime.utcnow().timestamp()}",
        "reason": reason,
        "expires_at": datetime.utcnow().isoformat(),
        "approved_by": "current_user",
    }


@router.get("/alerts")
async def get_rate_limit_alerts():
    """Get active rate limit alerts."""
    usage = get_mock_usage()
    alerts = []

    if usage["records_today"] > usage["limits"]["records"] * 0.8:
        alerts.append(
            {
                "type": "warning",
                "message": f"Approaching daily record limit: {usage['records_today']:,} / {usage['limits']['records']:,}",
                "percentage": (usage["records_today"] / usage["limits"]["records"])
                * 100,
                "created_at": datetime.utcnow().isoformat(),
            }
        )

    if usage["cost_today"] > usage["limits"]["cost"] * 0.9:
        alerts.append(
            {
                "type": "critical",
                "message": f"Near daily cost limit: ${usage['cost_today']:.2f} / ${usage['limits']['cost']:.2f}",
                "percentage": (usage["cost_today"] / usage["limits"]["cost"]) * 100,
                "created_at": datetime.utcnow().isoformat(),
            }
        )

    return {"alerts": alerts, "count": len(alerts)}
