use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::{AgentId, OperationId, WorkspaceId};

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InvocationSource {
    AdminTestRun,
    AgentToolCall,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InvocationLevel {
    Debug,
    Info,
    Warn,
    Error,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InvocationStatus {
    Ok,
    Error,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum UsagePeriod {
    #[serde(rename = "30m")]
    Last30Minutes,
    #[serde(rename = "1h")]
    LastHour,
    #[serde(rename = "6h")]
    Last6Hours,
    #[serde(rename = "24h")]
    Last24Hours,
    #[serde(rename = "7d")]
    Last7Days,
    #[serde(rename = "30d")]
    Last30Days,
    #[serde(rename = "90d")]
    Last90Days,
    #[serde(rename = "this_month")]
    ThisMonth,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct InvocationLog {
    pub id: crate::ids::InvocationLogId,
    pub workspace_id: WorkspaceId,
    pub agent_id: Option<AgentId>,
    pub operation_id: OperationId,
    pub source: InvocationSource,
    pub level: InvocationLevel,
    pub status: InvocationStatus,
    pub tool_name: String,
    pub message: String,
    pub request_id: Option<String>,
    pub status_code: Option<u16>,
    pub duration_ms: u64,
    pub error_kind: Option<String>,
    pub request_preview: Value,
    pub response_preview: Value,
    pub created_at: String,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UsageRollup {
    pub workspace_id: WorkspaceId,
    pub agent_id: Option<AgentId>,
    pub operation_id: Option<OperationId>,
    pub period: UsagePeriod,
    pub calls_total: u64,
    pub calls_ok: u64,
    pub calls_error: u64,
    pub p50_ms: u64,
    pub p95_ms: u64,
    pub p99_ms: u64,
}
