import json
from uuid import uuid4
from typing import Optional
from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy.orm import Session
from pydantic import BaseModel
from datetime import datetime

from backend.models.database import get_db, ProjectTemplate

router = APIRouter()


class TemplateField(BaseModel):
    key: str
    label: str
    field_type: str
    required: bool


class TemplateCreateRequest(BaseModel):
    name: str
    project_id: int
    template_type: str
    prompt_template: str
    output_format: str = "markdown"
    fields: list


class TemplateResponse(BaseModel):
    id: str
    project_id: int
    name: str
    template_type: str
    prompt_template: str
    output_format: str
    fields: list
    enabled: bool
    created_at: datetime
    updated_at: datetime

    class Config:
        from_attributes = True


def model_to_dict(template: ProjectTemplate) -> dict:
    """将ProjectTemplate模型转换为字典"""
    return {
        "id": template.id,
        "project_id": template.project_id,
        "name": template.name,
        "template_type": template.template_type,
        "prompt_template": template.prompt_template,
        "output_format": template.output_format,
        "fields": json.loads(template.fields) if template.fields else [],
        "enabled": template.enabled,
        "created_at": template.created_at.isoformat() if template.created_at else "",
        "updated_at": template.updated_at.isoformat() if template.updated_at else "",
    }


@router.get("/templates")
async def list_templates(
    project_id: Optional[int] = None,
    db: Session = Depends(get_db)
):
    """获取模板列表"""
    query = db.query(ProjectTemplate)
    if project_id:
        query = query.filter(ProjectTemplate.project_id == project_id)
    
    templates = query.all()
    return {"data": [model_to_dict(t) for t in templates]}


@router.get("/templates/{template_id}")
async def get_template(template_id: str, db: Session = Depends(get_db)):
    """获取模板详情"""
    template = db.query(ProjectTemplate).filter(ProjectTemplate.id == template_id).first()
    if not template:
        raise HTTPException(status_code=404, detail="Template not found")
    
    return model_to_dict(template)


@router.post("/templates")
async def create_template(
    request: TemplateCreateRequest,
    db: Session = Depends(get_db)
):
    """创建模板"""
    template = ProjectTemplate(
        id=str(uuid4()),
        project_id=request.project_id,
        name=request.name,
        template_type=request.template_type,
        prompt_template=request.prompt_template,
        output_format=request.output_format,
        fields=json.dumps(request.fields),
        enabled=True
    )
    db.add(template)
    db.commit()
    db.refresh(template)
    
    return model_to_dict(template)


@router.put("/templates/{template_id}")
async def update_template(
    template_id: str,
    request: TemplateCreateRequest,
    db: Session = Depends(get_db)
):
    """更新模板"""
    template = db.query(ProjectTemplate).filter(ProjectTemplate.id == template_id).first()
    if not template:
        raise HTTPException(status_code=404, detail="Template not found")
    
    template.name = request.name
    template.template_type = request.template_type
    template.prompt_template = request.prompt_template
    template.output_format = request.output_format
    template.fields = json.dumps(request.fields)
    
    db.commit()
    db.refresh(template)
    
    return model_to_dict(template)


@router.delete("/templates/{template_id}")
async def delete_template(template_id: str, db: Session = Depends(get_db)):
    """删除模板"""
    template = db.query(ProjectTemplate).filter(ProjectTemplate.id == template_id).first()
    if not template:
        raise HTTPException(status_code=404, detail="Template not found")
    
    db.delete(template)
    db.commit()
    
    return {"success": True}
