#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称：api_preset.py
模块描述：API 接口预设 Pydantic Schema

作者：czj
创建日期：2026-08-13
"""

from datetime import datetime
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Field, ConfigDict

from app.schemas.performance_output import CaptureRule


def to_camel(string: str) -> str:
    """Convert snake_case to camelCase"""
    components = string.split('_')
    return components[0] + ''.join(
        x if x[0].isdigit() else x.title()
        for x in components[1:]
    )


# ==================== 创建/更新 ====================

class ApiPresetCreate(BaseModel):
    """创建 API 接口预设"""
    name: str = Field(..., min_length=1, max_length=200, description="预设名称")
    description: str = Field("", description="描述")

    # 接口配置
    method: str = Field("GET", description="HTTP 方法 (GET/POST/PUT/DELETE)")
    target_url: str = Field(..., description="目标接口完整 URL")
    headers: Dict[str, str] = Field(default_factory=dict, description="自定义请求头")
    body: Optional[Any] = Field(None, description="静态请求体（与 body_template 互斥）")
    body_template: Optional[Dict[str, Any]] = Field(None, description="请求体模板")

    # 认证配置
    auth_required: bool = Field(True, description="是否需要登录 Token")
    sign_request: bool = Field(False, description="是否需要签名")
    account_key: str = Field("superadmin", description="使用账号 key")

    # 登录凭据配置
    credential_name: Optional[str] = Field(None, description="凭据名称，如'超级管理员'")
    login_username: Optional[str] = Field(None, description="自定义登录用户名，留空使用默认")
    login_password: Optional[str] = Field(None, description="自定义登录密码，留空使用默认")

    # 响应捕获
    capture_rules: Optional[List[CaptureRule]] = Field(None, description="捕获规则列表")

    model_config = ConfigDict(populate_by_name=True, alias_generator=to_camel)


class ApiPresetUpdate(BaseModel):
    """更新 API 接口预设（所有字段可选）"""
    name: Optional[str] = Field(None, min_length=1, max_length=200, description="预设名称")
    description: Optional[str] = Field(None, description="描述")
    method: Optional[str] = Field(None, description="HTTP 方法")
    target_url: Optional[str] = Field(None, description="目标接口完整 URL")
    headers: Optional[Dict[str, str]] = Field(None, description="自定义请求头")
    body: Optional[Any] = Field(None, description="静态请求体")
    body_template: Optional[Dict[str, Any]] = Field(None, description="请求体模板")
    auth_required: Optional[bool] = Field(None, description="是否需要登录 Token")
    sign_request: Optional[bool] = Field(None, description="是否需要签名")
    account_key: Optional[str] = Field(None, description="使用账号 key")
    credential_name: Optional[str] = Field(None, description="凭据名称")
    login_username: Optional[str] = Field(None, description="自定义登录用户名")
    login_password: Optional[str] = Field(None, description="自定义登录密码")
    capture_rules: Optional[List[CaptureRule]] = Field(None, description="捕获规则列表")

    model_config = ConfigDict(populate_by_name=True, alias_generator=to_camel)


# ==================== 响应 ====================

class ApiPresetResponse(BaseModel):
    """API 接口预设响应"""
    id: str
    name: str
    description: str = ""
    method: str = "GET"
    target_url: str = ""
    headers: Dict[str, str] = {}
    body: Optional[Any] = None
    body_template: Optional[Dict[str, Any]] = None
    auth_required: bool = True
    sign_request: bool = False
    account_key: str = "superadmin"
    credential_name: Optional[str] = None
    login_username: Optional[str] = None
    login_password: Optional[str] = None
    capture_rules: List[Dict[str, Any]] = []
    created_at: Optional[str] = None
    updated_at: Optional[str] = None

    model_config = ConfigDict(populate_by_name=True, alias_generator=to_camel)


class ApiPresetListItem(BaseModel):
    """API 接口预设列表项（简洁版）"""
    id: str
    name: str
    description: str = ""
    method: str = "GET"
    target_url: str = ""
    credential_name: Optional[str] = None
    updated_at: Optional[str] = None

    model_config = ConfigDict(populate_by_name=True, alias_generator=to_camel)


class ApiPresetListResponse(BaseModel):
    """API 接口预设列表响应"""
    total: int
    items: List[ApiPresetListItem]

    model_config = ConfigDict(populate_by_name=True, alias_generator=to_camel)