"""AI analysis endpoints — placeholder implementation for future AI integration."""

from datetime import datetime
from typing import Any, Optional

from fastapi import APIRouter, Depends, HTTPException, Query, status
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session

from app.database import get_db
from app.models.house import House
from app.models.user import User
from app.services.auth_service import get_current_user
from app.utils.helpers import generate_uuid, paginate

router = APIRouter()


# ── Schemas ────────────────────────────────────────────────────────────── #

class AnalyzeResponse(BaseModel):
    job_id: str
    status: str
    message: str


class SuggestionRead(BaseModel):
    id: str
    house_id: str
    type: str
    title: str
    description: Optional[str] = None
    status: str
    created_at: str


class JobRead(BaseModel):
    id: str
    house_id: str
    job_type: str
    status: str
    progress: int
    created_at: str
    completed_at: Optional[str] = None
    result: Optional[Any] = None


# ── In-memory store (placeholder until Celery/Redis is wired up) ───────── #
# In production, these would be database-backed models.
_ai_jobs: dict[str, dict[str, Any]] = {}
_ai_suggestions: dict[str, dict[str, Any]] = {}


# ── Endpoints ──────────────────────────────────────────────────────────── #

@router.post(
    "/api/houses/{hid}/ai/analyze",
    response_model=AnalyzeResponse,
    summary="触发 AI 分析",
)
def analyze_house(
    hid: str,
    db: Session = Depends(get_db),
    _: User = Depends(get_current_user),
):
    """Trigger AI analysis for a house.

    This is a placeholder endpoint.  In production it would enqueue a
    Celery task that runs AI models (hotspot detection, room
    classification, etc.) and writes results to the database.
    """
    house = db.query(House).filter(House.id == hid).first()
    if not house:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="房屋不存在",
        )

    job_id = generate_uuid()
    _ai_jobs[job_id] = {
        "id": job_id,
        "house_id": hid,
        "job_type": "full_analysis",
        "status": "queued",
        "progress": 0,
        "created_at": datetime.utcnow().isoformat(),
        "completed_at": None,
        "result": None,
    }

    return AnalyzeResponse(
        job_id=job_id,
        status="queued",
        message="AI 分析任务已加入队列",
    )


@router.get(
    "/api/houses/{hid}/ai/jobs",
    response_model=dict,
    summary="获取 AI 分析任务列表",
)
def list_ai_jobs(
    hid: str,
    page: int = Query(1, ge=1),
    size: int = Query(20, ge=1, le=100),
    db: Session = Depends(get_db),
    _: User = Depends(get_current_user),
):
    """List AI analysis jobs for a house (paginated)."""
    house = db.query(House).filter(House.id == hid).first()
    if not house:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="房屋不存在",
        )

    # In production this would query the database
    house_jobs = [
        JobRead(**job)
        for job in _ai_jobs.values()
        if job["house_id"] == hid
    ]

    # Manual pagination
    total = len(house_jobs)
    start = (page - 1) * size
    end = start + size
    items = house_jobs[start:end]
    pages = (total + size - 1) // size if total > 0 else 0

    return {
        "items": [j.model_dump() for j in items],
        "total": total,
        "page": page,
        "size": size,
        "pages": pages,
    }


@router.get(
    "/api/houses/{hid}/ai/suggestions",
    response_model=dict,
    summary="获取 AI 建议列表",
)
def list_ai_suggestions(
    hid: str,
    page: int = Query(1, ge=1),
    size: int = Query(20, ge=1, le=100),
    status_filter: Optional[str] = Query(None, alias="status"),
    db: Session = Depends(get_db),
    _: User = Depends(get_current_user),
):
    """List AI suggestions for a house (paginated)."""
    house = db.query(House).filter(House.id == hid).first()
    if not house:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="房屋不存在",
        )

    # In production this would query the database
    house_suggestions = [
        SuggestionRead(**s)
        for s in _ai_suggestions.values()
        if s["house_id"] == hid
        and (not status_filter or s["status"] == status_filter)
    ]

    # Manual pagination
    total = len(house_suggestions)
    start = (page - 1) * size
    end = start + size
    items = house_suggestions[start:end]
    pages = (total + size - 1) // size if total > 0 else 0

    return {
        "items": [s.model_dump() for s in items],
        "total": total,
        "page": page,
        "size": size,
        "pages": pages,
    }


@router.post("/api/ai/suggestions/{sid}/approve", summary="采纳 AI 建议")
def approve_suggestion(
    sid: str,
    db: Session = Depends(get_db),
    _: User = Depends(get_current_user),
):
    """Approve an AI suggestion.

    In production this would apply the suggestion to the house data and
    persist the change to the database.
    """
    suggestion = _ai_suggestions.get(sid)
    if not suggestion:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="建议不存在",
        )

    suggestion["status"] = "approved"
    return {"message": "建议已采纳", "suggestion_id": sid}


@router.post("/api/ai/suggestions/{sid}/reject", summary="拒绝 AI 建议")
def reject_suggestion(
    sid: str,
    db: Session = Depends(get_db),
    _: User = Depends(get_current_user),
):
    """Reject an AI suggestion."""
    suggestion = _ai_suggestions.get(sid)
    if not suggestion:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="建议不存在",
        )

    suggestion["status"] = "rejected"
    return {"message": "建议已拒绝", "suggestion_id": sid}
