"""
Dashboard API Routes - FastAPI routes for dashboard functionality
"""
from __future__ import annotations

import os
from datetime import datetime, timedelta, timezone
from typing import List, Optional

from fastapi import APIRouter, Depends, HTTPException, Request, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

from app.auth.jwt import verify_token, AuthError, issue_access_token
from app.dashboard.data import (
    create_user,
    create_organization,
    get_user_by_email,
    get_user_by_id,
    get_user_organization,
    update_user_login,
    update_user_profile,
    change_password,
    update_organization,
    create_api_key,
    get_organization_api_keys,
    revoke_api_key,
    get_dashboard_stats,
    get_organization_activities,
    get_usage_stats,
    get_available_plans,
    get_user_settings,
    update_user_settings,
    hash_password,
    verify_password,
    add_activity,
    get_team_members,
    invite_team_member_to_org,
    update_member_role,
    remove_team_member_from_org,
    get_subscription_details,
    upgrade_organization_plan,
    get_analytics_data,
    get_detailed_usage_analytics,
)
from app.dashboard.models import (
    AuthResponse,
    UserLogin,
    UserRegistration,
    OrganizationCreate,
    OrganizationUpdate,
    UserProfileUpdate,
    PasswordChange,
    ApiKeyCreate,
    MessageResponse,
    ErrorResponse,
    DashboardStats,
    UserProfile,
    OrganizationResponse,
    IndustryType,
    CompanySize,
    UserRole,
    ApiKeyResponse,
    ApiKeyWithSecret,
    ActivityItem,
    UsageStats,
    BillingPlan,
    UserSettings,
    TeamMember,
    TeamInvite,
    RoleUpdate,
    SubscriptionResponse,
    AnalyticsResponse,
    UsageAnalytics,
)
from app.observability.logging import get_logger


_logger = get_logger("dashboard.routes")

# Security
security = HTTPBearer()

# Router
router = APIRouter(prefix="/api/v1/dashboard", tags=["dashboard"])


# Auth dependency
async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)):
    """Verify JWT token and return current user."""
    try:
        token = credentials.credentials
        payload = verify_token(token)
        user_id = payload.get("sub")
        
        if not user_id:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Invalid token: no user ID"
            )
        
        user = await get_user_by_id(user_id)
        if not user or not user.get("is_active", True):
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="User not found or inactive"
            )
        
        return user
        
    except AuthError as e:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=f"Authentication failed: {str(e)}"
        )
    except Exception as e:
        _logger.error(f"Auth error: {e}")
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Authentication failed"
        )


# Authentication Routes
@router.post("/auth/register", response_model=MessageResponse)
async def register_user(user_data: UserRegistration):
    """Register a new user."""
    try:
        # Check if user already exists
        existing_user = await get_user_by_email(user_data.email)
        if existing_user:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="User with this email already exists"
            )
        
        # Create user
        password_hash = hash_password(user_data.password)
        user_id = await create_user(
            email=user_data.email,
            password_hash=password_hash,
            first_name=user_data.first_name,
            last_name=user_data.last_name
        )

        # Create a default organization for the new owner so the dashboard
        # works immediately (stats/usage/activity/api-keys are org-scoped).
        domain = str(user_data.email).split("@")[-1]
        company_slug = (domain.split(".")[0] if domain else "").strip()
        company_name = company_slug.replace("-", " ").replace("_", " ").strip().title()
        if not company_name:
            company_name = (
                f"{user_data.first_name} {user_data.last_name}".strip()
                or "My Organization"
            )
        await create_organization(
            name=company_name,
            industry=IndustryType.OTHER,
            size=CompanySize.SIZE_1_10,
            country="US",
            owner_id=user_id,
        )
        
        _logger.info(f"User registered successfully: {user_id}")
        return MessageResponse(message="User registered successfully")
        
    except HTTPException:
        raise
    except Exception as e:
        _logger.error(f"Registration error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Registration failed"
        )


@router.post("/auth/login", response_model=AuthResponse)
async def login_user(login_data: UserLogin):
    """Authenticate user and return access token."""
    try:
        # Get user by email
        user = await get_user_by_email(login_data.email)
        if not user:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Invalid credentials"
            )
        
        # Verify password
        if not verify_password(login_data.password, user["password_hash"]):
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Invalid credentials"
            )
        
        # Update last login
        await update_user_login(user["id"])
        
        # Get organization (auto-create a default org for owners if missing)
        organization = None
        org_data = await get_user_organization(user["id"])
        if not org_data and user.get("role") == "owner":
            domain = str(user["email"]).split("@")[-1]
            company_slug = (domain.split(".")[0] if domain else "").strip()
            company_name = company_slug.replace("-", " ").replace("_", " ").strip().title()
            if not company_name:
                company_name = (
                    f"{user.get('first_name', '')} {user.get('last_name', '')}".strip()
                    or "My Organization"
                )

            await create_organization(
                name=company_name,
                industry=IndustryType.OTHER,
                size=CompanySize.SIZE_1_10,
                country="US",
                owner_id=user["id"],
            )
            org_data = await get_user_organization(user["id"])

        if org_data:
            organization = OrganizationResponse(
                id=org_data["id"],
                name=org_data["name"],
                industry=org_data["industry"],
                size=org_data["size"],
                country=org_data["country"],
                website=org_data.get("website"),
                description=org_data.get("description"),
                created_at=org_data["created_at"],
                updated_at=org_data["updated_at"],
                plan=org_data["plan"],
                member_count=org_data["member_count"],
                owner_id=org_data["owner_id"],
            )
        
        # Issue JWT token
        token, expires_in = issue_access_token(
            subject=user["id"],
            org=org_data["id"] if org_data else None,
            plan=org_data["plan"] if org_data else "starter",
            scope=["dashboard:read", "dashboard:write", "api:manage"],
        )
        
        user_profile = UserProfile(
            id=user["id"],
            email=user["email"],
            first_name=user["first_name"],
            last_name=user["last_name"],
            role=UserRole(user["role"]),
            created_at=user["created_at"],
            last_login=user["last_login"],
            avatar_url=user.get("avatar_url"),
        )
        
        _logger.info(f"User logged in successfully: {user['id']}")
        return AuthResponse(
            access_token=token,
            refresh_token=None,
            token_type="Bearer",
            expires_in=expires_in,
            user=user_profile,
            organization=organization,
        )
        
    except HTTPException:
        raise
    except Exception as e:
        _logger.error(f"Login error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Login failed"
        )


# Organization Routes
@router.post("/organization", response_model=OrganizationResponse)
async def create_user_organization(
    org_data: OrganizationCreate,
    current_user: dict = Depends(get_current_user)
):
    """Create organization for current user."""
    try:
        # Check if user already has an organization
        existing_org = await get_user_organization(current_user["id"])
        if existing_org:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="User already has an organization"
            )
        
        # Create organization
        org_id = await create_organization(
            name=org_data.name,
            industry=org_data.industry,
            size=org_data.size,
            country=org_data.country,
            website=org_data.website,
            description=org_data.description,
            owner_id=current_user["id"],
        )
        
        # Get created organization
        org = await get_user_organization(current_user["id"])
        if not org:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="Failed to create organization"
            )
        
        return OrganizationResponse(
            id=org["id"],
            name=org["name"],
            industry=org["industry"],
            size=org["size"],
            country=org["country"],
            website=org.get("website"),
            description=org.get("description"),
            created_at=org["created_at"],
            updated_at=org["updated_at"],
            plan=org["plan"],
            member_count=org["member_count"],
            owner_id=org["owner_id"],
        )
        
    except HTTPException:
        raise
    except Exception as e:
        _logger.error(f"Organization creation error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Organization creation failed"
        )


@router.get("/organization", response_model=OrganizationResponse)
async def get_user_organization_info(current_user: dict = Depends(get_current_user)):
    """Get current user's organization."""
    try:
        org = await get_user_organization(current_user["id"])
        if not org:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Organization not found"
            )
        
        return OrganizationResponse(
            id=org["id"],
            name=org["name"],
            industry=org["industry"],
            size=org["size"],
            country=org["country"],
            website=org.get("website"),
            description=org.get("description"),
            created_at=org["created_at"],
            updated_at=org["updated_at"],
            plan=org["plan"],
            member_count=org["member_count"],
            owner_id=org["owner_id"],
        )
        
    except HTTPException:
        raise
    except Exception as e:
        _logger.error(f"Get organization error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to get organization"
        )


@router.put("/organization", response_model=MessageResponse)
async def update_user_organization(
    org_data: OrganizationUpdate,
    current_user: dict = Depends(get_current_user)
):
    """Update current user's organization."""
    try:
        org = await get_user_organization(current_user["id"])
        if not org:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Organization not found"
            )
        
        # Check if user is owner
        if org["owner_id"] != current_user["id"]:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Only organization owner can update details"
            )
        
        success = await update_organization(
            org_id=org["id"],
            name=org_data.name,
            industry=org_data.industry,
            size=org_data.size,
            country=org_data.country,
            website=org_data.website,
            description=org_data.description,
        )
        
        if not success:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="Update failed"
            )
        
        # Log activity
        await add_activity(
            org_id=org["id"],
            user_id=current_user["id"],
            activity_type="organization_updated",
            title="Organization Updated",
            description="Organization details were updated",
            icon="edit"
        )
        
        return MessageResponse(message="Organization updated successfully")
        
    except HTTPException:
        raise
    except Exception as e:
        _logger.error(f"Organization update error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Organization update failed"
        )


# User Profile Routes
@router.get("/profile", response_model=UserProfile)
async def get_user_profile(current_user: dict = Depends(get_current_user)):
    """Get current user's profile."""
    return UserProfile(
        id=current_user["id"],
        email=current_user["email"],
        first_name=current_user["first_name"],
        last_name=current_user["last_name"],
        role=UserRole(current_user["role"]),
        created_at=current_user["created_at"],
        last_login=current_user["last_login"],
        avatar_url=current_user.get("avatar_url"),
    )


@router.put("/profile", response_model=MessageResponse)
async def update_profile(
    profile_data: UserProfileUpdate,
    current_user: dict = Depends(get_current_user)
):
    """Update user profile."""
    try:
        success = await update_user_profile(
            user_id=current_user["id"],
            first_name=profile_data.first_name,
            last_name=profile_data.last_name,
        )
        
        if not success:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="Profile update failed"
            )
        
        return MessageResponse(message="Profile updated successfully")
        
    except HTTPException:
        raise
    except Exception as e:
        _logger.error(f"Profile update error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Profile update failed"
        )


@router.post("/profile/change-password", response_model=MessageResponse)
async def change_user_password(
    password_data: PasswordChange,
    current_user: dict = Depends(get_current_user)
):
    """Change user password."""
    try:
        # Verify current password
        if not verify_password(password_data.current_password, current_user["password_hash"]):
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Current password is incorrect"
            )
        
        # Hash new password and update
        new_password_hash = hash_password(password_data.new_password)
        success = await change_password(current_user["id"], new_password_hash)
        
        if not success:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="Password change failed"
            )
        
        return MessageResponse(message="Password changed successfully")
        
    except HTTPException:
        raise
    except Exception as e:
        _logger.error(f"Password change error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Password change failed"
        )


# API Key Management Routes
@router.get("/api-keys", response_model=List[ApiKeyResponse])
async def list_api_keys(current_user: dict = Depends(get_current_user)):
    """List user's organization API keys."""
    try:
        org = await get_user_organization(current_user["id"])
        if not org:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Organization not found"
            )
        
        return await get_organization_api_keys(org["id"])
        
    except HTTPException:
        raise
    except Exception as e:
        _logger.error(f"List API keys error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to list API keys"
        )


@router.post("/api-keys", response_model=ApiKeyWithSecret)
async def create_new_api_key(
    key_data: ApiKeyCreate,
    current_user: dict = Depends(get_current_user)
):
    """Create a new API key."""
    try:
        return await create_api_key(
            user_id=current_user["id"],
            name=key_data.name,
            scopes=key_data.scopes
        )
        
    except Exception as e:
        _logger.error(f"Create API key error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to create API key"
        )


@router.delete("/api-keys/{key_id}", response_model=MessageResponse)
async def revoke_api_key_endpoint(
    key_id: str,
    current_user: dict = Depends(get_current_user)
):
    """Revoke an API key."""
    try:
        success = await revoke_api_key(key_id, current_user["id"])
        if not success:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="API key not found"
            )
        
        return MessageResponse(message="API key revoked successfully")
        
    except HTTPException:
        raise
    except Exception as e:
        _logger.error(f"Revoke API key error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to revoke API key"
        )


# Dashboard Statistics Routes
@router.get("/stats", response_model=DashboardStats)
async def get_dashboard_statistics(current_user: dict = Depends(get_current_user)):
    """Get dashboard statistics."""
    try:
        org = await get_user_organization(current_user["id"])
        if not org:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Organization not found"
            )
        
        return await get_dashboard_stats(org["id"])
        
    except HTTPException:
        raise
    except Exception as e:
        _logger.error(f"Get dashboard stats error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to get dashboard statistics"
        )


@router.get("/activity", response_model=List[ActivityItem])
async def get_recent_activity(
    limit: int = 20,
    current_user: dict = Depends(get_current_user)
):
    """Get recent organization activity."""
    try:
        org = await get_user_organization(current_user["id"])
        if not org:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Organization not found"
            )
        
        return await get_organization_activities(org["id"], limit)
        
    except HTTPException:
        raise
    except Exception as e:
        _logger.error(f"Get activity error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to get activity"
        )


@router.get("/usage", response_model=List[UsageStats])
async def get_usage_analytics(
    days: int = 30,
    current_user: dict = Depends(get_current_user)
):
    """Get usage analytics."""
    try:
        org = await get_user_organization(current_user["id"])
        if not org:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Organization not found"
            )
        
        return await get_usage_stats(org["id"], days)
        
    except HTTPException:
        raise
    except Exception as e:
        _logger.error(f"Get usage stats error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to get usage statistics"
        )


# Billing Routes
@router.get("/billing/plans", response_model=List[BillingPlan])
async def get_billing_plans():
    """Get available billing plans."""
    try:
        return await get_available_plans()
    except Exception as e:
        _logger.error(f"Get billing plans error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to get billing plans"
        )


# Settings Routes
@router.get("/settings", response_model=UserSettings)
async def get_settings(current_user: dict = Depends(get_current_user)):
    """Get user settings."""
    try:
        return await get_user_settings(current_user["id"])
    except Exception as e:
        _logger.error(f"Get settings error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to get settings"
        )


@router.put("/settings", response_model=MessageResponse)
async def update_settings(
    settings: UserSettings,
    current_user: dict = Depends(get_current_user)
):
    """Update user settings."""
    try:
        success = await update_user_settings(current_user["id"], settings)
        if not success:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="Settings update failed"
            )
        
        return MessageResponse(message="Settings updated successfully")
    except HTTPException:
        raise
    except Exception as e:
        _logger.error(f"Update settings error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to update settings"
        )


# Team Management Routes
@router.get("/team/members", response_model=List[TeamMember])
async def get_team_members_endpoint(current_user: dict = Depends(get_current_user)):
    """Get organization team members."""
    try:
        org = await get_user_organization(current_user["id"])
        if not org:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Organization not found"
            )
        
        return await get_team_members(org["id"])
        
    except HTTPException:
        raise
    except Exception as e:
        _logger.error(f"Get team members error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to get team members"
        )


@router.post("/team/invite", response_model=MessageResponse)
async def invite_team_member(
    invite: TeamInvite,
    current_user: dict = Depends(get_current_user)
):
    """Invite a new team member."""
    try:
        org = await get_user_organization(current_user["id"])
        if not org:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Organization not found"
            )
        
        # Check if user has permission to invite
        if current_user["role"] not in ["owner", "admin"]:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Only owners and admins can invite team members"
            )
        
        success = await invite_team_member_to_org(
            org_id=org["id"],
            email=invite.email,
            role=invite.role,
            invited_by=current_user["id"],
            message=invite.message
        )
        
        if not success:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Failed to send invitation"
            )
        
        return MessageResponse(message="Team member invitation sent successfully")
        
    except HTTPException:
        raise
    except Exception as e:
        _logger.error(f"Invite team member error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to invite team member"
        )


@router.put("/team/members/{member_id}/role", response_model=MessageResponse)
async def update_team_member_role(
    member_id: str,
    role_update: RoleUpdate,
    current_user: dict = Depends(get_current_user)
):
    """Update team member role."""
    try:
        org = await get_user_organization(current_user["id"])
        if not org:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Organization not found"
            )
        
        # Check permissions
        if current_user["role"] not in ["owner", "admin"]:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Only owners and admins can update member roles"
            )
        
        success = await update_member_role(
            org_id=org["id"],
            member_id=member_id,
            new_role=role_update.role,
            updated_by=current_user["id"]
        )
        
        if not success:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Team member not found"
            )
        
        return MessageResponse(message="Team member role updated successfully")
        
    except HTTPException:
        raise
    except Exception as e:
        _logger.error(f"Update member role error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to update member role"
        )


@router.delete("/team/members/{member_id}", response_model=MessageResponse)
async def remove_team_member(
    member_id: str,
    current_user: dict = Depends(get_current_user)
):
    """Remove team member from organization."""
    try:
        org = await get_user_organization(current_user["id"])
        if not org:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Organization not found"
            )
        
        # Check permissions
        if current_user["role"] not in ["owner", "admin"]:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Only owners and admins can remove team members"
            )
        
        success = await remove_team_member_from_org(
            org_id=org["id"],
            member_id=member_id,
            removed_by=current_user["id"]
        )
        
        if not success:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Team member not found"
            )
        
        return MessageResponse(message="Team member removed successfully")
        
    except HTTPException:
        raise
    except Exception as e:
        _logger.error(f"Remove team member error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to remove team member"
        )


# Subscription and Billing Routes
@router.get("/billing/subscription", response_model=SubscriptionResponse)
async def get_subscription_info(current_user: dict = Depends(get_current_user)):
    """Get current subscription information."""
    try:
        org = await get_user_organization(current_user["id"])
        if not org:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Organization not found"
            )
        
        return await get_subscription_details(org["id"])
        
    except HTTPException:
        raise
    except Exception as e:
        _logger.error(f"Get subscription error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to get subscription information"
        )


@router.post("/billing/upgrade", response_model=MessageResponse)
async def upgrade_subscription(
    request: Request,
    current_user: dict = Depends(get_current_user)
):
    """Upgrade subscription plan."""
    try:
        body = await request.json()
        plan_id = body.get("plan_id")
        billing_interval = body.get("billing_interval")
        
        if not plan_id:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Plan ID is required"
            )
        
        org = await get_user_organization(current_user["id"])
        if not org:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Organization not found"
            )
        
        # Check if user is owner
        if current_user["role"] != "owner":
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Only organization owner can upgrade subscription"
            )
        
        success = await upgrade_organization_plan(
            org_id=org["id"],
            new_plan=plan_id,
            upgraded_by=current_user["id"],
            billing_interval=billing_interval,
        )
        
        if not success:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Failed to upgrade subscription"
            )
        
        return MessageResponse(message="Subscription upgraded successfully")
        
    except HTTPException:
        raise
    except Exception as e:
        _logger.error(f"Upgrade subscription error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to upgrade subscription"
        )


# Analytics Routes
@router.get("/analytics/overview", response_model=List[AnalyticsResponse])
async def get_analytics_overview(
    time_range: str = "7d",
    current_user: dict = Depends(get_current_user)
):
    """Get analytics overview data."""
    try:
        org = await get_user_organization(current_user["id"])
        if not org:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Organization not found"
            )
        
        return await get_analytics_data(org["id"], time_range)
        
    except HTTPException:
        raise
    except Exception as e:
        _logger.error(f"Get analytics error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to get analytics data"
        )


@router.get("/analytics/usage", response_model=UsageAnalytics)
async def get_usage_analytics_endpoint(
    time_range: str = "30d",
    current_user: dict = Depends(get_current_user)
):
    """Get detailed usage analytics."""
    try:
        org = await get_user_organization(current_user["id"])
        if not org:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Organization not found"
            )
        
        return await get_detailed_usage_analytics(org["id"], time_range)
        
    except HTTPException:
        raise
    except Exception as e:
        _logger.error(f"Get usage analytics error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to get usage analytics"
        )
