"""
订阅管理API端点
"""
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from typing import List, Dict, Optional
from datetime import datetime, timedelta
import secrets
import hashlib

from app.config import settings
from app.services.subscription import SubscriptionService

router = APIRouter()
security = HTTPBearer()

# 订阅服务实例
subscription_service = SubscriptionService()

# 请求和响应模型
from pydantic import BaseModel

class SubscriptionPlan(BaseModel):
    """订阅计划"""
    id: str
    name: str
    price: float
    features: List[str]
    limits: Dict

class CreateSubscriptionRequest(BaseModel):
    """创建订阅请求"""
    plan_id: str
    email: str
    name: Optional[str] = None
    company: Optional[str] = None
    payment_method: str = "stripe"

class SubscriptionResponse(BaseModel):
    """订阅响应"""
    id: str
    user_id: str
    plan_id: str
    api_key: str
    status: str
    price: float
    features: List[str]
    limits: Dict
    created_at: datetime
    expires_at: datetime

class UpdateSubscriptionRequest(BaseModel):
    """更新订阅请求"""
    plan_id: Optional[str] = None
    status: Optional[str] = None

# 依赖项
async def authenticate_api_key(
    credentials: HTTPAuthorizationCredentials = Depends(security)
) -> Dict:
    """验证API密钥"""
    api_key = credentials.credentials
    
    # 检查API密钥是否有效
    subscription = subscription_service.get_subscription_by_api_key(api_key)
    if not subscription:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="无效的API密钥"
        )
    
    # 检查订阅是否有效
    if subscription["status"] != "active":
        raise HTTPException(
            status_code=status.HTTP_402_PAYMENT_REQUIRED,
            detail="订阅已过期或已取消"
        )
    
    # 检查是否过期
    if subscription["expires_at"] < datetime.now():
        subscription_service.update_subscription_status(
            subscription["id"],
            "expired"
        )
        raise HTTPException(
            status_code=status.HTTP_402_PAYMENT_REQUIRED,
            detail="订阅已过期"
        )
    
    return subscription

async def check_rate_limit(
    subscription: Dict = Depends(authenticate_api_key)
) -> Dict:
    """检查API调用限制"""
    user_id = subscription["user_id"]
    
    # 检查日调用限制
    daily_calls = subscription_service.get_daily_api_calls(user_id)
    daily_limit = subscription["limits"]["daily_calls"]
    
    if daily_calls >= daily_limit:
        raise HTTPException(
            status_code=status.HTTP_429_TOO_MANY_REQUESTS,
            detail=f"日API调用次数已达上限: {daily_limit}"
        )
    
    # 记录API调用
    subscription_service.record_api_call(user_id, "endpoint_name")
    
    return subscription

# API端点
@router.get("/plans", response_model=List[SubscriptionPlan])
async def get_subscription_plans():
    """获取所有订阅计划"""
    plans = []
    for plan_id, plan_info in settings.SUBSCRIPTION_PLANS.items():
        plans.append(SubscriptionPlan(
            id=plan_id,
            name=plan_info["name"],
            price=plan_info["price"],
            features=plan_info["features"],
            limits=plan_info["limits"]
        ))
    return plans

@router.post("/subscriptions", response_model=SubscriptionResponse)
async def create_subscription(request: CreateSubscriptionRequest):
    """创建订阅"""
    
    # 检查计划是否存在
    if request.plan_id not in settings.SUBSCRIPTION_PLANS:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"订阅计划不存在: {request.plan_id}"
        )
    
    # 获取计划信息
    plan_info = settings.SUBSCRIPTION_PLANS[request.plan_id]
    
    # 生成API密钥
    api_key = subscription_service.generate_api_key(request.email)
    
    # 创建用户
    user = subscription_service.create_user(
        email=request.email,
        name=request.name,
        company=request.company
    )
    
    # 创建订阅
    subscription = subscription_service.create_subscription(
        user_id=user["id"],
        plan_id=request.plan_id,
        api_key=api_key,
        price=plan_info["price"],
        features=plan_info["features"],
        limits=plan_info["limits"]
    )
    
    # 记录支付信息（简化版，实际应调用支付网关）
    if plan_info["price"] > 0:
        subscription_service.record_payment(
            user_id=user["id"],
            subscription_id=subscription["id"],
            amount=plan_info["price"],
            payment_method=request.payment_method,
            status="completed"
        )
    
    return SubscriptionResponse(
        id=subscription["id"],
        user_id=user["id"],
        plan_id=subscription["plan_id"],
        api_key=api_key,
        status=subscription["status"],
        price=subscription["price"],
        features=subscription["features"],
        limits=subscription["limits"],
        created_at=subscription["created_at"],
        expires_at=subscription["expires_at"]
    )

@router.get("/subscriptions/{subscription_id}", response_model=SubscriptionResponse)
async def get_subscription(
    subscription_id: str,
    subscription: Dict = Depends(authenticate_api_key)
):
    """获取订阅详情"""
    
    # 检查权限
    if subscription["id"] != subscription_id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权访问此订阅信息"
        )
    
    # 获取订阅详情
    subscription_detail = subscription_service.get_subscription(subscription_id)
    if not subscription_detail:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="订阅不存在"
        )
    
    return SubscriptionResponse(**subscription_detail)

@router.put("/subscriptions/{subscription_id}", response_model=SubscriptionResponse)
async def update_subscription(
    subscription_id: str,
    request: UpdateSubscriptionRequest,
    subscription: Dict = Depends(authenticate_api_key)
):
    """更新订阅"""
    
    # 检查权限
    if subscription["id"] != subscription_id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权更新此订阅"
        )
    
    # 更新订阅
    updated_subscription = subscription_service.update_subscription(
        subscription_id=subscription_id,
        plan_id=request.plan_id,
        status=request.status
    )
    
    if not updated_subscription:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="订阅不存在"
        )
    
    return SubscriptionResponse(**updated_subscription)

@router.delete("/subscriptions/{subscription_id}")
async def cancel_subscription(
    subscription_id: str,
    subscription: Dict = Depends(authenticate_api_key)
):
    """取消订阅"""
    
    # 检查权限
    if subscription["id"] != subscription_id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权取消此订阅"
        )
    
    # 取消订阅
    success = subscription_service.cancel_subscription(subscription_id)
    
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="订阅不存在"
        )
    
    return {
        "success": True,
        "message": "订阅已取消"
    }

@router.get("/subscriptions/{subscription_id}/usage")
async def get_subscription_usage(
    subscription_id: str,
    subscription: Dict = Depends(authenticate_api_key)
):
    """获取订阅使用情况"""
    
    # 检查权限
    if subscription["id"] != subscription_id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权访问此使用信息"
        )
    
    # 获取使用统计
    usage_stats = subscription_service.get_usage_stats(subscription_id)
    
    return {
        "subscription_id": subscription_id,
        "current_plan": subscription["plan_id"],
        "usage": usage_stats,
        "limits": subscription["limits"],
        "remaining": {
            "daily_calls": subscription["limits"]["daily_calls"] - usage_stats.get("daily_calls", 0),
            "monthly_calls": subscription["limits"]["monthly_calls"] - usage_stats.get("monthly_calls", 0)
        }
    }

@router.post("/subscriptions/{subscription_id}/renew")
async def renew_subscription(
    subscription_id: str,
    subscription: Dict = Depends(authenticate_api_key)
):
    """续订订阅"""
    
    # 检查权限
    if subscription["id"] != subscription_id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权续订此订阅"
        )
    
    # 检查订阅状态
    if subscription["status"] not in ["active", "expired"]:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="只有有效或过期的订阅可以续订"
        )
    
    # 续订订阅
    renewed_subscription = subscription_service.renew_subscription(
        subscription_id=subscription_id,
        payment_method="stripe"  # 简化，实际应根据用户选择
    )
    
    if not renewed_subscription:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="续订失败"
        )
    
    return {
        "success": True,
        "message": "订阅已成功续订",
        "new_expires_at": renewed_subscription["expires_at"]
    }

@router.post("/subscriptions/{subscription_id}/upgrade")
async def upgrade_subscription(
    subscription_id: str,
    new_plan_id: str,
    subscription: Dict = Depends(authenticate_api_key)
):
    """升级订阅计划"""
    
    # 检查权限
    if subscription["id"] != subscription_id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权升级此订阅"
        )
    
    # 检查新计划是否存在
    if new_plan_id not in settings.SUBSCRIPTION_PLANS:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"订阅计划不存在: {new_plan_id}"
        )
    
    # 检查是否已经是该计划
    if subscription["plan_id"] == new_plan_id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="已经是该订阅计划"
        )
    
    # 升级订阅
    upgraded_subscription = subscription_service.upgrade_subscription(
        subscription_id=subscription_id,
        new_plan_id=new_plan_id
    )
    
    if not upgraded_subscription:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="升级失败"
        )
    
    return {
        "success": True,
        "message": "订阅已成功升级",
        "new_plan": new_plan_id,
        "new_price": settings.SUBSCRIPTION_PLANS[new_plan_id]["price"],
        "new_features": settings.SUBSCRIPTION_PLANS[new_plan_id]["features"]
    }