from fastapi import APIRouter, Depends, Query
from fastapi.responses import StreamingResponse
from sqlalchemy.ext.asyncio import AsyncSession
from datetime import datetime
from typing import Optional
import io

from ...db import get_session
from ...auth import get_current_account
from ...services.roles import require_steward
from ...services.audit_service import AuditService

router = APIRouter(prefix="/api/v2/audit", tags=["audit"])


@router.get("/events")
async def get_audit_events(
    start_date: Optional[datetime] = Query(None),
    end_date: Optional[datetime] = Query(None),
    actor_id: Optional[str] = Query(None),
    action: Optional[str] = Query(None),
    limit: int = Query(100, le=1000),
    db: AsyncSession = Depends(get_session),
    account_id: str = Depends(get_current_account),
    _user=Depends(require_steward),
):
    """Get audit events with filtering"""
    service = AuditService(db)

    events = await service.get_audit_trail(
        account_id=account_id,
        start_date=start_date,
        end_date=end_date,
        actor_id=actor_id,
        action=action,
        limit=limit,
    )

    return {
        "events": [
            {
                "id": e.id,
                "timestamp": e.timestamp.isoformat(),
                "actor_id": e.actor_id,
                "action": e.action,
                "object_type": e.object_type,
                "record_count": len(e.record_ids),
                "justification": e.justification,
            }
            for e in events
        ]
    }


@router.get("/export")
async def export_audit_trail(
    format: str = Query("csv"),
    start_date: Optional[datetime] = Query(None),
    end_date: Optional[datetime] = Query(None),
    db: AsyncSession = Depends(get_session),
    account_id: str = Depends(get_current_account),
    _user=Depends(require_steward),
):
    """Export audit trail"""
    service = AuditService(db)

    events = await service.get_audit_trail(
        account_id=account_id, start_date=start_date, end_date=end_date, limit=10000
    )

    if format == "csv":
        csv_data = await service.export_audit_csv(events)

        return StreamingResponse(
            io.BytesIO(csv_data.encode()),
            media_type="text/csv",
            headers={
                "Content-Disposition": f"attachment; filename=audit_trail_{datetime.now().date()}.csv"
            },
        )
