from django.shortcuts import get_object_or_404, render

from .models import AgentAuditLog, NotificationRecord


def log_list(request):
    # 处理历史页支持按批次、产品和状态筛选。
    scenario_id = (request.GET.get("scenario_id") or "").strip()
    keyword = (request.GET.get("keyword") or "").strip()
    logs = AgentAuditLog.objects.all()
    if scenario_id:
        logs = logs.filter(scenario_id=scenario_id)
    if keyword:
        logs = logs.filter(product_name__icontains=keyword) | logs.filter(batch_id__icontains=keyword)
    return render(
        request,
        "audit/log_list.html",
        {
            "logs": logs,
            "selected_scenario_id": scenario_id,
            "keyword": keyword,
        },
    )


def log_detail(request, log_id: int):
    # 详情页只负责按主键加载审计快照并渲染；
    # 所有脱敏和字段映射都应在服务层完成。
    audit_log = get_object_or_404(AgentAuditLog, pk=log_id)
    notifications = NotificationRecord.objects.filter(
        conversation_id=audit_log.conversation_id,
        batch_id=audit_log.batch_id,
    )
    return render(
        request,
        "audit/log_detail.html",
        {"log": audit_log, "notifications": notifications},
    )
