// src/monitoring/logger.rs
use super::metrics::SessionSummary;
use chrono::Local;
use std::path::PathBuf;
use tokio::fs::OpenOptions;
use tokio::io::AsyncWriteExt;
use tokio::sync::Mutex;

/// Logs session summaries to JSONL files
pub struct SessionLogger {
    log_dir: PathBuf,
    file: Mutex<Option<tokio::fs::File>>,
}

impl SessionLogger {
    pub fn new(log_dir: PathBuf) -> Self {
        Self {
            log_dir,
            file: Mutex::new(None),
        }
    }

    /// Log a completed session summary
    pub async fn log_session(&self, summary: &SessionSummary) {
        if let Err(e) = self.write_session(summary).await {
            eprintln!("Failed to log session: {}", e);
        }
    }

    async fn write_session(&self, summary: &SessionSummary) -> anyhow::Result<()> {
        let mut file_guard = self.file.lock().await;

        // Open file if not already open
        if file_guard.is_none() {
            let filename = format!(
                "sessions_{}.jsonl",
                Local::now().format("%Y%m%d")
            );
            let filepath = self.log_dir.join(filename);

            tokio::fs::create_dir_all(&self.log_dir).await?;

            let file = OpenOptions::new()
                .create(true)
                .append(true)
                .open(&filepath)
                .await?;

            *file_guard = Some(file);
        }

        if let Some(file) = file_guard.as_mut() {
            let json_line = serde_json::to_string(summary)?;
            file.write_all(json_line.as_bytes()).await?;
            file.write_all(b"\n").await?;
            file.flush().await?;
        }

        Ok(())
    }
}

/// Logs metrics snapshots periodically
pub struct MetricsLogger {
    log_dir: PathBuf,
}

impl MetricsLogger {
    pub fn new(log_dir: PathBuf) -> Self {
        Self { log_dir }
    }

    /// Log a metrics snapshot
    pub async fn log_metrics(&self, state: &super::metrics::DashboardState) -> anyhow::Result<()> {
        let filename = format!(
            "metrics_{}.jsonl",
            Local::now().format("%Y%m%d")
        );
        let filepath = self.log_dir.join(filename);

        tokio::fs::create_dir_all(&self.log_dir).await?;

        let mut file = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&filepath)
            .await?;

        let snapshot = serde_json::json!({
            "timestamp": Local::now().format("%Y-%m-%d %H:%M:%S").to_string(),
            "global": state.global,
            "instance_count": state.instances.len(),
            "proxy_count": state.proxies.len(),
        });

        let json_line = serde_json::to_string(&snapshot)?;
        file.write_all(json_line.as_bytes()).await?;
        file.write_all(b"\n").await?;
        file.flush().await?;

        Ok(())
    }
}