from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from datetime import datetime

from ..database import get_db
from ..models import TopicField, TopicConfigField
from ..schemas import (
    TopicFieldBase, TopicFieldResponse,
    TopicConfigFieldBase, TopicConfigFieldResponse
)
from .auth import get_current_user

router = APIRouter(prefix="/api/topic-config", tags=["topic-config"])


@router.get("/fields", response_model=List[TopicFieldResponse])
def list_fields(
    include_inactive: bool = False,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user)
):
    query = db.query(TopicField)
    if not include_inactive:
        query = query.filter(TopicField.is_active == True)
    return query.order_by(TopicField.sort_order, TopicField.id).all()


@router.post("/fields", response_model=TopicFieldResponse)
def create_field(
    data: TopicFieldBase,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user)
):
    existing = db.query(TopicField).filter(TopicField.name == data.name).first()
    if existing:
        raise HTTPException(status_code=400, detail=f"领域 '{data.name}' 已存在")
    field = TopicField(**data.model_dump())
    db.add(field)
    db.commit()
    db.refresh(field)
    return field


@router.put("/fields/{field_id}", response_model=TopicFieldResponse)
def update_field(
    field_id: int,
    data: TopicFieldBase,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user)
):
    field = db.query(TopicField).filter(TopicField.id == field_id).first()
    if not field:
        raise HTTPException(status_code=404, detail="领域不存在")
    for k, v in data.model_dump(exclude_unset=True).items():
        setattr(field, k, v)
    db.commit()
    db.refresh(field)
    return field


@router.delete("/fields/{field_id}")
def delete_field(
    field_id: int,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user)
):
    field = db.query(TopicField).filter(TopicField.id == field_id).first()
    if not field:
        raise HTTPException(status_code=404, detail="领域不存在")
    field.is_active = False
    db.commit()
    return {"ok": True, "message": "领域已删除"}


@router.get("/fields/{field_id}/scoring", response_model=List[TopicConfigFieldResponse])
def get_scoring_fields(
    field_id: int,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user)
):
    field = db.query(TopicField).filter(TopicField.id == field_id).first()
    if not field:
        raise HTTPException(status_code=404, detail="领域不存在")
    return db.query(TopicConfigField).filter(
        TopicConfigField.field_id == field_id
    ).order_by(TopicConfigField.sort_order).all()


@router.post("/fields/{field_id}/scoring", response_model=TopicConfigFieldResponse)
def create_scoring_field(
    field_id: int,
    data: TopicConfigFieldBase,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user)
):
    field = db.query(TopicField).filter(TopicField.id == field_id).first()
    if not field:
        raise HTTPException(status_code=404, detail="领域不存在")

    existing = db.query(TopicConfigField).filter(
        TopicConfigField.field_id == field_id,
        TopicConfigField.key == data.key
    ).first()
    if existing:
        raise HTTPException(status_code=400, detail=f"字段 '{data.key}' 已存在")

    config = TopicConfigField(field_id=field_id, **data.model_dump())
    db.add(config)
    db.commit()
    db.refresh(config)
    return config


@router.put("/scoring/{config_id}", response_model=TopicConfigFieldResponse)
def update_scoring_field(
    config_id: int,
    data: TopicConfigFieldBase,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user)
):
    cfg = db.query(TopicConfigField).filter(TopicConfigField.id == config_id).first()
    if not cfg:
        raise HTTPException(status_code=404, detail="字段不存在")
    for k, v in data.model_dump(exclude_unset=True).items():
        setattr(cfg, k, v)
    db.commit()
    db.refresh(cfg)
    return cfg


@router.delete("/scoring/{config_id}")
def delete_scoring_field(
    config_id: int,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user)
):
    cfg = db.query(TopicConfigField).filter(TopicConfigField.id == config_id).first()
    if not cfg:
        raise HTTPException(status_code=404, detail="字段不存在")
    db.delete(cfg)
    db.commit()
    return {"ok": True}


@router.post("/fields/{field_id}/scoring/batch", response_model=List[TopicConfigFieldResponse])
def batch_create_scoring_fields(
    field_id: int,
    fields: List[TopicConfigFieldBase],
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user)
):
    field = db.query(TopicField).filter(TopicField.id == field_id).first()
    if not field:
        raise HTTPException(status_code=404, detail="领域不存在")

    results = []
    for f in fields:
        existing = db.query(TopicConfigField).filter(
            TopicConfigField.field_id == field_id,
            TopicConfigField.key == f.key
        ).first()
        if existing:
            for k, v in f.model_dump(exclude_unset=True).items():
                setattr(existing, k, v)
            results.append(existing)
        else:
            obj = TopicConfigField(field_id=field_id, **f.model_dump())
            db.add(obj)
            results.append(obj)
    db.commit()
    for r in results:
        db.refresh(r)
    return results