//! Logs command - view service logs

use anyhow::{Context, Result};
use std::process::Command;

/// Run the logs command
pub async fn run(service: Option<String>, lines: u32, follow: bool) -> Result<()> {
    let project_root = find_project_root()?;
    let librechat_dir = project_root.join("deploy/librechat");

    if !librechat_dir.exists() {
        anyhow::bail!("LibreChat not configured. Run 'sea-forge setup' first.");
    }

    let mut cmd = Command::new("docker");
    cmd.args(["compose", "logs"]);
    cmd.arg(format!("--tail={}", lines));

    if follow {
        cmd.arg("-f");
    }

    if let Some(ref svc) = service {
        cmd.arg(svc);
    }

    cmd.current_dir(&librechat_dir);

    // Run interactively
    let status = cmd.status().context("Failed to run docker compose logs")?;

    if !status.success() {
        anyhow::bail!("Failed to get logs");
    }

    Ok(())
}

fn find_project_root() -> Result<std::path::PathBuf> {
    let current = std::env::current_dir()?;
    let mut path = current.as_path();

    loop {
        if path.join("justfile").exists() && path.join("Cargo.toml").exists() {
            return Ok(path.to_path_buf());
        }
        path = path.parent().context("Could not find SEA project root")?;
    }
}
