"""
询问笔录策略 API 路由
基于 1+4+6 架构：1套通用底层策略 + 4大行业模块 + 6类案情适配
"""

from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel
from typing import Optional, List
import json

from ...core.permission import require_login
from ...core.database import get_db
from ...services.inquiry_strategy_service import InquiryStrategyService

router = APIRouter()
service = InquiryStrategyService()


class GenerateStrategyRequest(BaseModel):
    industry_category: str
    industry_subcategory: Optional[str] = None
    case_type: str
    supplementary_content: Optional[str] = ""
    attachment_ids: List[int] = []


class SaveStrategyRequest(BaseModel):
    strategy_content: str


@router.get("/cases/{case_id}/inquiry-strategy")
async def get_inquiry_strategy(
    case_id: str,
    user: dict = Depends(require_login),
    db=Depends(get_db)
):
    """获取案件的询问笔录策略（如果不存在则返回空数据和智能推荐）"""
    try:
        result = await service.get_or_create_strategy(case_id, user['userId'], db)
        return result
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取策略失败: {str(e)}")


@router.post("/cases/{case_id}/inquiry-strategy/generate")
async def generate_strategy(
    case_id: str,
    request: GenerateStrategyRequest,
    user: dict = Depends(require_login),
    db=Depends(get_db)
):
    """生成询问笔录策略（基于1+4+6架构）"""
    
    # 验证参数
    valid_industries = ['market_regulation', 'agriculture', 'culture_tourism', 'commerce', 'other']
    valid_case_types = ['minor', 'general', 'intentional', 'negligent', 'multiple', 'complex']
    
    if request.industry_category not in valid_industries:
        raise HTTPException(status_code=400, detail="无效的行业分类")
    
    if request.case_type not in valid_case_types:
        raise HTTPException(status_code=400, detail="无效的案情类型")
    
    try:
        result = await service.generate_strategy(
            case_id=case_id,
            user_id=user['userId'],
            industry_category=request.industry_category,
            industry_subcategory=request.industry_subcategory or '',
            case_type=request.case_type,
            supplementary_content=request.supplementary_content or '',
            attachment_ids=request.attachment_ids or [],
            is_auto_recommended=False,
            db=db
        )
        return result
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"生成策略失败: {str(e)}")


@router.put("/cases/{case_id}/inquiry-strategy/{strategy_id}")
async def save_inquiry_strategy(
    case_id: str,
    strategy_id: int,
    request: SaveStrategyRequest,
    user: dict = Depends(require_login),
    db=Depends(get_db)
):
    """保存编辑后的策略内容"""
    try:
        result = await service.save_strategy(strategy_id, {'strategy_content': request.strategy_content}, db)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"保存失败: {str(e)}")


@router.get("/cases/{case_id}/inquiry-strategy/{strategy_id}/export")
async def export_strategy(
    case_id: str,
    strategy_id: int,
    format: str = Query("word", pattern="^(word|pdf)$"),
    user: dict = Depends(require_login),
    db=Depends(get_db)
):
    """导出策略为Word或PDF格式"""
    
    try:
        file_path = await service.export_strategy(strategy_id, format, db)
        
        from fastapi.responses import FileResponse
        
        if format == 'word':
            media_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
            filename = f'inquiry_strategy_{strategy_id}.docx'
        else:
            media_type = 'application/pdf'
            filename = f'inquiry_strategy_{strategy_id}.pdf'
        
        return FileResponse(
            path=file_path,
            media_type=media_type,
            filename=filename
        )
    except FileNotFoundError:
        raise HTTPException(status_code=404, detail="策略不存在")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"导出失败: {str(e)}")


@router.delete("/cases/{case_id}/inquiry-strategy/{strategy_id}")
async def delete_inquiry_strategy(
    case_id: str,
    strategy_id: int,
    user: dict = Depends(require_login),
    db=Depends(get_db)
):
    """删除询问笔录策略"""
    try:
        conn, cur = db
        await cur.execute("DELETE FROM inquiry_strategies WHERE id = %s AND case_id = %s", (strategy_id, case_id))
        await conn.commit()
        
        return {"success": True, "message": "删除成功"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除失败: {str(e)}")
