use std::fs::OpenOptions;
use std::io;
use std::sync::Mutex;

use tracing_subscriber::EnvFilter;

fn default_filter() -> EnvFilter {
    if flatland_client_lib::harvest_debug_verbose() {
        EnvFilter::try_from_default_env()
            .unwrap_or_else(|_| "warn,flatland.harvest=debug,info".into())
    } else {
        EnvFilter::try_from_default_env().unwrap_or_else(|_| "warn".into())
    }
}

fn init_to_file(path: &str, filter: EnvFilter) -> io::Result<()> {
    if let Some(parent) = std::path::Path::new(path).parent() {
        if !parent.as_os_str().is_empty() {
            std::fs::create_dir_all(parent)?;
        }
    }
    let file = OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)?;
    tracing_subscriber::fmt()
        .with_env_filter(filter)
        .with_writer(Mutex::new(file))
        .with_ansi(false)
        .init();
    Ok(())
}

/// Default init for auth/inventory subcommands (stderr).
pub fn init() -> io::Result<()> {
    if flatland_client_lib::harvest_debug_verbose() {
        init_to_file("data/logs/harvest-debug.log", default_filter())?;
        eprintln!(
            "Harvest debug log: data/logs/harvest-debug.log (not stderr — safe for TUI play)"
        );
    } else {
        tracing_subscriber::fmt()
            .with_env_filter(default_filter())
            .init();
    }
    Ok(())
}

/// Ratatui play must not write tracing to stderr — it corrupts the alternate screen.
pub fn init_for_play() -> io::Result<()> {
    let path = if flatland_client_lib::harvest_debug_verbose() {
        "data/logs/harvest-debug.log"
    } else {
        "data/logs/flatland3-client.log"
    };
    init_to_file(path, default_filter())?;
    Ok(())
}
