from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func, desc
from typing import Optional
from datetime import datetime

from app.database import get_db
from app.models.message import MessageLog
from app.schemas.common import Response, PageResponse
from app.services.auth_service import get_current_user

router = APIRouter()


def _parse_dt(s):
    if not s:
        return None
    try:
        return datetime.fromisoformat(s.replace('Z', ''))
    except Exception:
        return None


@router.get("/logs", response_model=Response[PageResponse[dict]])
async def list_message_logs(
    page: int = 1,
    page_size: int = 50,
    msg_type: Optional[str] = None,
    direction: Optional[str] = None,
    status: Optional[str] = None,
    start_time: Optional[str] = Query(None),
    end_time: Optional[str] = Query(None),
    db: AsyncSession = Depends(get_db),
    _ = Depends(get_current_user),
):
    query = select(MessageLog).order_by(desc(MessageLog.received_at))
    if msg_type:
        query = query.where(MessageLog.msg_type == msg_type)
    if direction:
        query = query.where(MessageLog.direction == direction)
    if status:
        query = query.where(MessageLog.status == status)
    _sd = _parse_dt(start_time)
    if _sd:
        query = query.where(MessageLog.received_at >= _sd)
    _ed = _parse_dt(end_time)
    if _ed:
        query = query.where(MessageLog.received_at <= _ed)

    total = (await db.execute(select(func.count()).select_from(query.subquery()))).scalar()
    result = await db.execute(query.offset((page - 1) * page_size).limit(page_size))
    items = []
    for log in result.scalars():
        items.append({
            "id": log.id,
            "msg_id": log.msg_id,
            "msg_type": log.msg_type,
            "direction": log.direction,
            "source": log.source,
            "status": log.status,
            "error_msg": log.error_msg,
            "process_time": log.process_time,
            "received_at": log.received_at,
        })
    return Response.ok(PageResponse(total=total, page=page, page_size=page_size, items=items))


@router.get("/logs/{log_id}", response_model=Response[dict])
async def get_message_log(log_id: int, db: AsyncSession = Depends(get_db), _ = Depends(get_current_user)):
    result = await db.execute(select(MessageLog).where(MessageLog.id == log_id))
    log = result.scalar_one_or_none()
    if not log:
        return Response.error("报文记录不存在", code=404)
    return Response.ok({
        "id": log.id,
        "msg_type": log.msg_type,
        "direction": log.direction,
        "raw_data": log.raw_data,
        "parsed_data": log.parsed_data,
        "status": log.status,
        "received_at": log.received_at,
    })
