#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称：performance_output.py
模块描述：性能测试任务输出查询 API 路由

提供从响应体捕获的字段值查询接口，供前端展示和 REF 引用验证。

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

import logging
from typing import Optional

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import select, func, desc
from sqlalchemy.ext.asyncio import AsyncSession

from app.database import get_db
from app.models.performance_output import PerformanceTaskOutput
from app.schemas.performance_output import (
    PerformanceTaskOutputResponse,
    PerformanceTaskOutputListResponse,
)

logger = logging.getLogger(__name__)

router = APIRouter()


@router.get("/outputs", response_model=PerformanceTaskOutputListResponse)
async def list_outputs(
    task_id: Optional[str] = Query(None, description="按任务ID过滤"),
    key: Optional[str] = Query(None, description="按键名过滤"),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    db: AsyncSession = Depends(get_db),
):
    """
    获取任务输出列表（分页）

    支持按 task_id 和 key 过滤，用于 REF 引用验证和前端展示。
    """
    query = select(PerformanceTaskOutput)
    count_query = select(func.count()).select_from(PerformanceTaskOutput)

    if task_id:
        query = query.where(PerformanceTaskOutput.task_id == task_id)
        count_query = count_query.where(PerformanceTaskOutput.task_id == task_id)
    if key:
        query = query.where(PerformanceTaskOutput.key == key)
        count_query = count_query.where(PerformanceTaskOutput.key == key)

    total = (await db.execute(count_query)).scalar() or 0

    query = (
        query.order_by(desc(PerformanceTaskOutput.created_at))
        .offset((page - 1) * page_size)
        .limit(page_size)
    )
    result = await db.execute(query)
    items = list(result.scalars().all())

    return PerformanceTaskOutputListResponse(
        total=total,
        items=[PerformanceTaskOutputResponse(**item.to_dict()) for item in items],
    )


@router.get("/outputs/{output_id}", response_model=PerformanceTaskOutputResponse)
async def get_output(
    output_id: int,
    db: AsyncSession = Depends(get_db),
):
    """获取单个任务输出详情"""
    output = await db.get(PerformanceTaskOutput, output_id)
    if not output:
        raise HTTPException(status_code=404, detail="输出记录不存在")
    return PerformanceTaskOutputResponse(**output.to_dict())


@router.get("/tasks/{task_id}/outputs", response_model=PerformanceTaskOutputListResponse)
async def get_task_outputs(
    task_id: str,
    key: Optional[str] = Query(None, description="按键名过滤"),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    db: AsyncSession = Depends(get_db),
):
    """
    获取某个任务的所有输出

    便捷接口，直接按 task_id 查询，可指定 key 过滤特定字段。
    """
    query = select(PerformanceTaskOutput).where(
        PerformanceTaskOutput.task_id == task_id
    )
    count_query = (
        select(func.count())
        .select_from(PerformanceTaskOutput)
        .where(PerformanceTaskOutput.task_id == task_id)
    )

    if key:
        query = query.where(PerformanceTaskOutput.key == key)
        count_query = count_query.where(PerformanceTaskOutput.key == key)

    total = (await db.execute(count_query)).scalar() or 0

    query = (
        query.order_by(PerformanceTaskOutput.created_at.asc())
        .offset((page - 1) * page_size)
        .limit(page_size)
    )
    result = await db.execute(query)
    items = list(result.scalars().all())

    return PerformanceTaskOutputListResponse(
        total=total,
        items=[PerformanceTaskOutputResponse(**item.to_dict()) for item in items],
    )