"""
Dashboard Data Access Layer - Database operations for dashboard functionality
"""
from __future__ import annotations

import hashlib
import hmac
import secrets
import time
import uuid
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Optional
from uuid import UUID

from app.auth.api_keys import Plan, PLAN_CONFIGS
from app.dashboard.models import (
    ActivityItem,
    AnalyticsResponse,
    ApiKeyResponse,
    ApiKeyWithSecret,
    BillingPlan,
    DashboardStats,
    IndustryType,
    CompanySize,
    NotificationSettings,
    OrganizationResponse,
    PaymentMethod,
    SecuritySettings,
    SubscriptionResponse,
    TeamMember,
    TimeSeriesDataPoint,
    UserProfile,
    UserRole,
    UserSettings,
    UsageAnalytics,
    UsageStats,
)
from app.observability.logging import get_logger
from app.storage.database import get_connection, get_transaction


_logger = get_logger("dashboard.data")


class DataAccessError(Exception):
    pass


class UserNotFoundError(DataAccessError):
    pass


class OrganizationNotFoundError(DataAccessError):
    pass


class ApiKeyNotFoundError(DataAccessError):
    pass


# User Operations
async def create_user(
    email: str,
    password_hash: str,
    first_name: str,
    last_name: str
) -> str:
    """Create a new user and return user ID."""
    async with get_connection() as conn:
        user_id = await conn.fetchval("""
            INSERT INTO users (email, password_hash, first_name, last_name, role)
            VALUES ($1, $2, $3, $4, 'owner')
            RETURNING id
        """, email.lower(), password_hash, first_name, last_name)
        
        _logger.info(f"Created user {user_id} with email {email}")
        return str(user_id)


async def get_user_by_email(email: str) -> Optional[Dict[str, Any]]:
    """Get user by email address."""
    async with get_connection() as conn:
        row = await conn.fetchrow("""
            SELECT id, email, password_hash, first_name, last_name, role,
                   organization_id, avatar_url, is_active, last_login_at,
                   created_at, updated_at
            FROM users 
            WHERE email = $1
        """, email.lower())
        
        if row:
            return {
                "id": str(row["id"]),
                "email": row["email"],
                "password_hash": row["password_hash"],
                "first_name": row["first_name"],
                "last_name": row["last_name"],
                "role": row["role"],
                "organization_id": str(row["organization_id"]) if row["organization_id"] else None,
                "avatar_url": row["avatar_url"],
                "is_active": row["is_active"],
                "last_login": row["last_login_at"],
                "created_at": row["created_at"],
                "updated_at": row["updated_at"]
            }
        return None


async def get_user_by_id(user_id: str) -> Optional[Dict[str, Any]]:
    """Get user by ID."""
    async with get_connection() as conn:
        row = await conn.fetchrow("""
            SELECT id, email, password_hash, first_name, last_name, role,
                   organization_id, avatar_url, is_active, last_login_at,
                   created_at, updated_at
            FROM users 
            WHERE id = $1
        """, UUID(user_id))
        
        if row:
            return {
                "id": str(row["id"]),
                "email": row["email"],
                "password_hash": row["password_hash"],
                "first_name": row["first_name"],
                "last_name": row["last_name"],
                "role": row["role"],
                "organization_id": str(row["organization_id"]) if row["organization_id"] else None,
                "avatar_url": row["avatar_url"],
                "is_active": row["is_active"],
                "last_login": row["last_login_at"],
                "created_at": row["created_at"],
                "updated_at": row["updated_at"]
            }
        return None


async def update_user_login(user_id: str) -> None:
    """Update user's last login timestamp."""
    async with get_connection() as conn:
        await conn.execute("""
            UPDATE users 
            SET last_login_at = NOW(), updated_at = NOW()
            WHERE id = $1
        """, UUID(user_id))


async def update_user_profile(
    user_id: str,
    first_name: Optional[str] = None,
    last_name: Optional[str] = None
) -> bool:
    """Update user profile information."""
    updates = []
    params = []
    param_count = 0
    
    if first_name is not None:
        param_count += 1
        updates.append(f"first_name = ${param_count}")
        params.append(first_name)
    
    if last_name is not None:
        param_count += 1
        updates.append(f"last_name = ${param_count}")
        params.append(last_name)
    
    if not updates:
        return True
    
    param_count += 1
    updates.append(f"updated_at = NOW()")
    params.append(UUID(user_id))
    
    async with get_connection() as conn:
        result = await conn.execute(f"""
            UPDATE users 
            SET {', '.join(updates)}
            WHERE id = ${param_count}
        """, *params)
        
        return result == "UPDATE 1"


async def change_password(user_id: str, new_password_hash: str) -> bool:
    """Change user password."""
    async with get_connection() as conn:
        result = await conn.execute("""
            UPDATE users 
            SET password_hash = $1, updated_at = NOW()
            WHERE id = $2
        """, new_password_hash, UUID(user_id))
        
        return result == "UPDATE 1"


# Organization Operations
async def create_organization(
    name: str,
    industry: IndustryType,
    size: CompanySize,
    country: str,
    website: Optional[str] = None,
    description: Optional[str] = None,
    owner_id: str = None,
) -> str:
    """Create a new organization and return organization ID."""
    async with get_transaction() as conn:
        # Create organization
        org_id = await conn.fetchval("""
            INSERT INTO organizations (name, industry, size, country, website, description, owner_id, plan)
            VALUES ($1, $2, $3, $4, $5, $6, $7, 'starter')
            RETURNING id
        """, name, industry.value, size.value, country, website, description, UUID(owner_id) if owner_id else None)
        
        # Update user's organization
        if owner_id:
            await conn.execute("""
                UPDATE users 
                SET organization_id = $1, updated_at = NOW()
                WHERE id = $2
            """, org_id, UUID(owner_id))
        
        _logger.info(f"Created organization {org_id} for user {owner_id}")
        return str(org_id)


async def get_organization_by_id(org_id: str) -> Optional[Dict[str, Any]]:
    """Get organization by ID."""
    async with get_connection() as conn:
        row = await conn.fetchrow("""
            SELECT o.id, o.name, o.industry, o.size, o.country, o.website, 
                   o.description, o.plan, o.owner_id, o.is_active,
                   o.created_at, o.updated_at,
                   COUNT(u.id) as member_count
            FROM organizations o
            LEFT JOIN users u ON u.organization_id = o.id AND u.is_active = true
            WHERE o.id = $1
            GROUP BY o.id, o.name, o.industry, o.size, o.country, o.website, 
                     o.description, o.plan, o.owner_id, o.is_active,
                     o.created_at, o.updated_at
        """, UUID(org_id))
        
        if row:
            return {
                "id": str(row["id"]),
                "name": row["name"],
                "industry": row["industry"],
                "size": row["size"],
                "country": row["country"],
                "website": row["website"],
                "description": row["description"],
                "plan": row["plan"],
                "owner_id": str(row["owner_id"]) if row["owner_id"] else None,
                "is_active": row["is_active"],
                "created_at": row["created_at"],
                "updated_at": row["updated_at"],
                "member_count": row["member_count"]
            }
        return None


async def get_user_organization(user_id: str) -> Optional[Dict[str, Any]]:
    """Get organization for a user."""
    user = await get_user_by_id(user_id)
    if not user or not user.get("organization_id"):
        return None
    
    return await get_organization_by_id(user["organization_id"])


async def update_organization(
    org_id: str,
    name: Optional[str] = None,
    industry: Optional[IndustryType] = None,
    size: Optional[CompanySize] = None,
    country: Optional[str] = None,
    website: Optional[str] = None,
    description: Optional[str] = None,
) -> bool:
    """Update organization information."""
    updates = []
    params = []
    param_count = 0
    
    if name is not None:
        param_count += 1
        updates.append(f"name = ${param_count}")
        params.append(name)
    
    if industry is not None:
        param_count += 1
        updates.append(f"industry = ${param_count}")
        params.append(industry.value)
    
    if size is not None:
        param_count += 1
        updates.append(f"size = ${param_count}")
        params.append(size.value)
    
    if country is not None:
        param_count += 1
        updates.append(f"country = ${param_count}")
        params.append(country)
    
    if website is not None:
        param_count += 1
        updates.append(f"website = ${param_count}")
        params.append(website)
    
    if description is not None:
        param_count += 1
        updates.append(f"description = ${param_count}")
        params.append(description)
    
    if not updates:
        return True
    
    param_count += 1
    updates.append(f"updated_at = NOW()")
    params.append(UUID(org_id))
    
    async with get_connection() as conn:
        result = await conn.execute(f"""
            UPDATE organizations 
            SET {', '.join(updates)}
            WHERE id = ${param_count}
        """, *params)
        
        return result == "UPDATE 1"


# API Key Operations
async def create_api_key(
    user_id: str,
    name: str,
    scopes: List[str]
) -> ApiKeyWithSecret:
    """Create a new API key for user's organization."""
    user = await get_user_by_id(user_id)
    if not user:
        raise UserNotFoundError(f"User {user_id} not found")
    
    org_id = user.get("organization_id")
    if not org_id:
        raise OrganizationNotFoundError("User not associated with organization")
    
    # Generate secure API key
    key_id = str(uuid.uuid4())
    key_secret = secrets.token_urlsafe(32)
    api_key = f"sk-{key_secret}"
    
    now = datetime.now(timezone.utc)
    key_data = {
        "id": key_id,
        "name": name,
        "key": api_key,
        "key_prefix": api_key[:12],  # sk-xxxxxxxx
        "organization_id": org_id,
        "created_by": user_id,
        "created_at": now,
        "last_used_at": None,
        "is_active": True,
        "scopes": scopes,
        "usage_count": 0,
    }
    
    _api_keys[key_id] = key_data
    
    # Log activity
    await add_activity(
        org_id=org_id,
        user_id=user_id,
        activity_type="api_key_created",
        title="API Key Created",
        description=f"New API key '{name}' was created",
        icon="plus"
    )
    
    return ApiKeyWithSecret(
        id=key_id,
        name=name,
        key=api_key,
        key_prefix=key_data["key_prefix"],
        created_at=now,
        last_used_at=None,
        is_active=True,
        scopes=scopes,
        usage_count=0,
    )


async def get_organization_api_keys(org_id: str) -> List[ApiKeyResponse]:
    """Get all API keys for an organization."""
    keys = []
    for key_data in _api_keys.values():
        if key_data["organization_id"] == org_id and key_data["is_active"]:
            keys.append(ApiKeyResponse(
                id=key_data["id"],
                name=key_data["name"],
                key_prefix=key_data["key_prefix"],
                created_at=key_data["created_at"],
                last_used_at=key_data["last_used_at"],
                is_active=key_data["is_active"],
                scopes=key_data["scopes"],
                usage_count=key_data["usage_count"],
            ))
    
    return sorted(keys, key=lambda x: x.created_at, reverse=True)


async def revoke_api_key(key_id: str, user_id: str) -> bool:
    """Revoke an API key."""
    if key_id not in _api_keys:
        return False
    
    key_data = _api_keys[key_id]
    key_data["is_active"] = False
    key_data["revoked_at"] = datetime.now(timezone.utc)
    key_data["revoked_by"] = user_id
    
    # Log activity
    user = await get_user_by_id(user_id)
    if user and user.get("organization_id"):
        await add_activity(
            org_id=user["organization_id"],
            user_id=user_id,
            activity_type="api_key_revoked",
            title="API Key Revoked",
            description=f"API key '{key_data['name']}' was revoked",
            icon="ban"
        )
    
    return True


# Dashboard Statistics
async def get_dashboard_stats(org_id: str) -> DashboardStats:
    """Get dashboard statistics for an organization."""
    org = await get_organization_by_id(org_id)
    if not org:
        raise OrganizationNotFoundError(f"Organization {org_id} not found")
    
    # Get current month usage
    now = datetime.now(timezone.utc)
    start_of_month = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
    
    # Simulate usage data
    api_usage_current_month = 1250
    plan_limits = PLAN_CONFIGS.get(Plan(org["plan"]))
    api_usage_limit = plan_limits.requests_per_month if plan_limits else 30000
    
    # Count active API keys
    active_keys = sum(1 for key in _api_keys.values() 
                     if key["organization_id"] == org_id and key["is_active"])
    
    return DashboardStats(
        api_usage_current_month=api_usage_current_month,
        api_usage_limit=api_usage_limit,
        success_rate=98.5,
        active_api_keys=active_keys,
        current_plan=org["plan"],
        plan_display_name=org["plan"].title(),
        total_requests_today=85,
        total_requests_this_month=api_usage_current_month,
        avg_response_time_ms=245.0,
        error_rate=1.5,
    )


# Activity Log
async def add_activity(
    org_id: str,
    user_id: Optional[str],
    activity_type: str,
    title: str,
    description: str,
    icon: str
) -> str:
    """Add an activity log entry."""
    activity_id = str(uuid.uuid4())
    now = datetime.now(timezone.utc)
    
    user_name = None
    if user_id:
        user = await get_user_by_id(user_id)
        if user:
            user_name = f"{user['first_name']} {user['last_name']}"
    
    activity = {
        "id": activity_id,
        "org_id": org_id,
        "user_id": user_id,
        "user_name": user_name,
        "type": activity_type,
        "title": title,
        "description": description,
        "icon": icon,
        "timestamp": now,
    }
    
    _activities.append(activity)
    
    # Keep only last 100 activities per org
    org_activities = [a for a in _activities if a["org_id"] == org_id]
    if len(org_activities) > 100:
        # Remove oldest activities
        _activities[:] = [a for a in _activities if a["org_id"] != org_id or 
                         a in sorted(org_activities, key=lambda x: x["timestamp"], reverse=True)[:100]]
    
    return activity_id


async def get_organization_activities(org_id: str, limit: int = 20) -> List[ActivityItem]:
    """Get recent activities for an organization."""
    org_activities = [a for a in _activities if a["org_id"] == org_id]
    org_activities.sort(key=lambda x: x["timestamp"], reverse=True)
    
    return [
        ActivityItem(
            id=activity["id"],
            type=activity["type"],
            title=activity["title"],
            description=activity["description"],
            timestamp=activity["timestamp"],
            icon=activity["icon"],
            user_id=activity["user_id"],
            user_name=activity["user_name"],
        )
        for activity in org_activities[:limit]
    ]


# Usage Analytics
async def get_usage_stats(org_id: str, days: int = 30) -> List[UsageStats]:
    """Get usage statistics for the past N days."""
    # Simulate usage data
    stats = []
    now = datetime.now(timezone.utc)
    
    for i in range(days):
        date = now - timedelta(days=i)
        # Simulate varying usage
        base_requests = 40 + (i % 7) * 10  # Higher on weekends
        requests = base_requests + secrets.randbelow(20)
        errors = requests // 50 + secrets.randbelow(3)
        response_time = 200.0 + secrets.randbelow(100)
        
        stats.append(UsageStats(
            date=date.strftime("%Y-%m-%d"),
            requests=requests,
            errors=errors,
            avg_response_time_ms=response_time,
        ))
    
    return list(reversed(stats))


# Billing Plans
async def get_available_plans() -> List[BillingPlan]:
    """Get available billing plans."""
    plans = [
        BillingPlan(
            id="starter",
            name="starter",
            display_name="Starter",
            price=4900,  # $49.00
            currency="USD",
            interval="month",
            description="Perfect for individual sales reps",
            features=[
                {"name": "1,000 API calls/month", "included": True},
                {"name": "Real-time conversation analysis", "included": True},
                {"name": "Basic lead scoring", "included": True},
                {"name": "Email support", "included": True},
                {"name": "Dashboard analytics", "included": True},
                {"name": "Advanced AI coaching", "included": False},
                {"name": "CRM integrations", "included": False},
                {"name": "Custom training data", "included": False},
            ],
            limits={"api_calls": 1000, "api_keys": 3},
        ),
        BillingPlan(
            id="professional",
            name="professional",
            display_name="Professional",
            price=14900,  # $149.00
            currency="USD",
            interval="month",
            description="Ideal for small to medium teams",
            features=[
                {"name": "10,000 API calls/month", "included": True},
                {"name": "Advanced AI coaching", "included": True},
                {"name": "Predictive lead scoring", "included": True},
                {"name": "CRM integrations", "included": True},
                {"name": "Priority support", "included": True},
                {"name": "Custom training data", "included": True},
                {"name": "White-label solutions", "included": False},
                {"name": "24/7 phone support", "included": False},
            ],
            limits={"api_calls": 10000, "api_keys": 10},
            is_popular=True,
        ),
        BillingPlan(
            id="enterprise",
            name="enterprise",
            display_name="Enterprise",
            price=49900,  # $499.00
            currency="USD",
            interval="month",
            description="For large sales organizations",
            features=[
                {"name": "100,000 API calls/month", "included": True},
                {"name": "White-label solutions", "included": True},
                {"name": "Custom AI model training", "included": True},
                {"name": "Dedicated success manager", "included": True},
                {"name": "24/7 phone support", "included": True},
                {"name": "On-premise deployment", "included": True},
                {"name": "SLA guarantees", "included": True},
                {"name": "Priority support queue", "included": True},
            ],
            limits={"api_calls": 100000, "api_keys": -1},
        ),
    ]
    
    return plans


# User Settings
async def get_user_settings(user_id: str) -> UserSettings:
    """Get user settings."""
    # Default settings - in production, load from database
    return UserSettings(
        notifications=NotificationSettings(
            email_notifications=True,
            usage_alerts=True,
            security_alerts=True,
            billing_alerts=True,
        ),
        security=SecuritySettings(
            two_factor_enabled=False,
            session_timeout_minutes=480,
        )
    )


async def update_user_settings(user_id: str, settings: UserSettings) -> bool:
    """Update user settings."""
    # In production, save to database
    _logger.info(f"Updated settings for user {user_id}")
    return True


# Helper functions for password hashing
def hash_password(password: str) -> str:
    """Hash a password using PBKDF2."""
    salt = secrets.token_hex(16)
    password_hash = hashlib.pbkdf2_hmac('sha256', password.encode(), salt.encode(), 100000)
    return f"{salt}:{password_hash.hex()}"


def verify_password(password: str, password_hash: str) -> bool:
    """Verify a password against its hash."""
    try:
        salt, hash_hex = password_hash.split(':')
        password_check = hashlib.pbkdf2_hmac('sha256', password.encode(), salt.encode(), 100000)
        return hmac.compare_digest(hash_hex, password_check.hex())
    except ValueError:
        return False


# Initialize demo data
async def init_demo_data():
    """Initialize demo data for testing."""
    # Create demo user
    demo_user_id = await create_user(
        email="admin@salesai.com",
        password_hash=hash_password("SalesAI2026!"),
        first_name="Sales",
        last_name="Admin"
    )
    
    # Create demo organization
    demo_org_id = await create_organization(
        name="Demo Company",
        industry=IndustryType.TECHNOLOGY,
        size=CompanySize.SIZE_11_50,
        country="US",
        website="https://demo-company.com",
        description="A demo company for testing purposes",
        owner_id=demo_user_id
    )
    
    # Create demo API key
    await create_api_key(
        user_id=demo_user_id,
        name="Production API Key",
        scopes=["api:read", "api:write"]
    )
    
    # Add some demo activities
    await add_activity(
        org_id=demo_org_id,
        user_id=demo_user_id,
        activity_type="user_signup",
        title="Account Created",
        description="Demo user signed up and created organization",
        icon="user-plus"
    )
    
    _logger.info("Demo data initialized successfully")


# Team Management Functions
async def get_team_members(org_id: str) -> List[TeamMember]:
    """Get all team members for an organization."""
    members = []
    for user in _users.values():
        if user.get("organization_id") == org_id:
            members.append(TeamMember(
                id=user["id"],
                email=user["email"],
                first_name=user["first_name"],
                last_name=user["last_name"],
                role=UserRole(user["role"]),
                status="active",
                joined_at=user["created_at"],
                last_active=user.get("last_login"),
                invited_by=None  # TODO: track who invited the user
            ))
    return members


async def invite_team_member_to_org(
    org_id: str, 
    email: str, 
    role: UserRole, 
    invited_by: str, 
    message: Optional[str] = None
) -> bool:
    """Invite a user to join an organization."""
    # In production, send actual email invitation
    _logger.info(f"Team member invitation sent to {email} for org {org_id}")
    
    # Add activity log
    await add_activity(
        org_id=org_id,
        user_id=invited_by,
        activity_type="team_invite_sent",
        title="Team Member Invited",
        description=f"Invitation sent to {email} as {role}",
        icon="user-plus"
    )
    
    return True


async def update_member_role(
    org_id: str, 
    member_id: str, 
    new_role: UserRole, 
    updated_by: str
) -> bool:
    """Update a team member's role."""
    user = _users.get(member_id)
    if not user or user.get("organization_id") != org_id:
        return False
    
    old_role = user["role"]
    user["role"] = new_role
    
    # Add activity log
    await add_activity(
        org_id=org_id,
        user_id=updated_by,
        activity_type="member_role_updated",
        title="Member Role Updated",
        description=f"Updated {user['first_name']} {user['last_name']} from {old_role} to {new_role}",
        icon="user-check"
    )
    
    return True


async def remove_team_member_from_org(
    org_id: str, 
    member_id: str, 
    removed_by: str
) -> bool:
    """Remove a team member from organization."""
    user = _users.get(member_id)
    if not user or user.get("organization_id") != org_id:
        return False
    
    # In production, handle user cleanup properly
    user["organization_id"] = None
    user["is_active"] = False
    
    # Add activity log
    await add_activity(
        org_id=org_id,
        user_id=removed_by,
        activity_type="member_removed",
        title="Team Member Removed",
        description=f"Removed {user['first_name']} {user['last_name']} from organization",
        icon="user-minus"
    )
    
    return True


# Billing and Subscription Functions
async def get_subscription_details(org_id: str) -> SubscriptionResponse:
    """Get subscription details for an organization."""
    org = await get_organization_by_id(org_id)
    if not org:
        raise OrganizationNotFoundError(f"Organization {org_id} not found")
    
    # Mock subscription data
    return SubscriptionResponse(
        id=str(uuid.uuid4()),
        organization_id=org_id,
        plan=org["plan"],
        status="active",
        billing_interval="month",
        current_period_start=datetime.now(timezone.utc).replace(day=1),
        current_period_end=datetime.now(timezone.utc).replace(day=28),
        cancel_at_period_end=False,
        created_at=org["created_at"],
        updated_at=org["updated_at"]
    )


async def upgrade_organization_plan(
    org_id: str, 
    new_plan: str, 
    upgraded_by: str,
    billing_interval: Optional[str] = None
) -> bool:
    """Upgrade organization plan."""
    org = _organizations.get(org_id)
    if not org:
        return False
    
    old_plan = org["plan"]
    org["plan"] = new_plan
    org["updated_at"] = datetime.now(timezone.utc)
    
    # Add activity log
    await add_activity(
        org_id=org_id,
        user_id=upgraded_by,
        activity_type="plan_upgraded",
        title="Plan Upgraded",
        description=f"Upgraded from {old_plan} to {new_plan}",
        icon="arrow-up"
    )
    
    return True


# Analytics Functions
async def get_analytics_data(org_id: str, time_range: str) -> List[AnalyticsResponse]:
    """Get analytics overview data."""
    # Mock analytics data
    now = datetime.now(timezone.utc)
    days = int(time_range.rstrip('d')) if time_range.endswith('d') else 7
    
    # Generate sample data points
    data_points = []
    for i in range(days):
        timestamp = now - timedelta(days=days-i-1)
        data_points.append(TimeSeriesDataPoint(
            timestamp=timestamp,
            value=100 + (i * 10) + (i % 3 * 5),  # Mock trending data
            label=f"Day {i+1}"
        ))
    
    return [
        AnalyticsResponse(
            metric_name="API Requests",
            time_range=time_range,
            data_points=data_points,
            total=sum(dp.value for dp in data_points),
            average=sum(dp.value for dp in data_points) / len(data_points),
            change_percent=15.3
        ),
        AnalyticsResponse(
            metric_name="Success Rate",
            time_range=time_range,
            data_points=[TimeSeriesDataPoint(timestamp=dp.timestamp, value=98.5) for dp in data_points],
            total=98.5,
            average=98.5,
            change_percent=2.1
        )
    ]


async def get_detailed_usage_analytics(org_id: str, time_range: str) -> UsageAnalytics:
    """Get detailed usage analytics."""
    now = datetime.now(timezone.utc)
    days = int(time_range.rstrip('d')) if time_range.endswith('d') else 30
    
    # Generate sample time series data
    requests_data = []
    errors_data = []
    response_times = []
    
    for i in range(days):
        timestamp = now - timedelta(days=days-i-1)
        requests_data.append(TimeSeriesDataPoint(
            timestamp=timestamp,
            value=120 + (i * 5) + (i % 7 * 3),
            label=f"Requests"
        ))
        errors_data.append(TimeSeriesDataPoint(
            timestamp=timestamp,
            value=2 + (i % 5),
            label=f"Errors"
        ))
        response_times.append(TimeSeriesDataPoint(
            timestamp=timestamp,
            value=200 + (i % 10 * 20),
            label=f"Response Time (ms)"
        ))
    
    return UsageAnalytics(
        requests_over_time=requests_data,
        errors_over_time=errors_data,
        response_times=response_times,
        top_endpoints=[
            {"endpoint": "/api/v1/voice/session", "requests": 1250, "percentage": 45.2},
            {"endpoint": "/api/v1/dashboard/stats", "requests": 890, "percentage": 32.1},
            {"endpoint": "/api/v1/dashboard/usage", "requests": 630, "percentage": 22.7},
        ],
        geographic_distribution=[
            {"country": "US", "requests": 2100, "percentage": 75.8},
            {"country": "CA", "requests": 420, "percentage": 15.2},
            {"country": "UK", "requests": 250, "percentage": 9.0},
        ],
        peak_usage_hours=[9, 10, 11, 14, 15, 16]
    )
