from typing import Any, Dict, List

from sqlalchemy import text

from app.db import engine


def list_business_events(limit: int = 100) -> List[Dict[str, Any]]:
    sql = text("""
        SELECT
            id::text,
            event_type,
            task_id::text,
            action_run_id::text,
            conversation_id,
            contact_id,
            payload,
            created_by,
            created_at
        FROM business_events
        ORDER BY created_at DESC
        LIMIT :limit
    """)

    with engine.begin() as conn:
        rows = conn.execute(sql, {"limit": limit}).mappings().all()

    return [dict(row) for row in rows]


def list_action_runs(limit: int = 100) -> List[Dict[str, Any]]:
    sql = text("""
        SELECT
            id::text,
            conversation_id,
            contact_id,
            source_system,
            model,
            provider,
            decision_source,
            action_decision,
            action_result,
            total_tokens,
            cost,
            needs_review,
            created_at
        FROM action_runs
        ORDER BY created_at DESC
        LIMIT :limit
    """)

    with engine.begin() as conn:
        rows = conn.execute(sql, {"limit": limit}).mappings().all()

    return [dict(row) for row in rows]
