//! CLI driver — exercises the full repository surface against an
//! on-disk SQLite file in a temporary directory.

use std::process::ExitCode;

use sqlite_storage_spike::{
    repo::NewBookmark, BookmarkRepository, LocalDatabaseRepository, SettingsRepository,
};
use tracing::info;

fn main() -> ExitCode {
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
        )
        .init();

    if let Err(e) = run() {
        eprintln!("error: {e}");
        return ExitCode::from(1);
    }
    ExitCode::SUCCESS
}

fn run() -> Result<(), Box<dyn std::error::Error>> {
    let tmp = tempfile::tempdir()?;
    let db_path = tmp.path().join("chanora.sqlite");
    info!(target: "spike", "opening {}", db_path.display());

    let repo = LocalDatabaseRepository::open(&db_path)?;
    info!(target: "spike", "schema version = {}", repo.schema_version()?);

    let id_a = repo.insert(NewBookmark {
        server_name: "Vigorous Pro",
        server_host: "cn.teamspeak.app",
        identity_ref: "identity.primary",
        nickname: Some("ChanoraPoC"),
    })?;
    let id_b = repo.insert(NewBookmark {
        server_name: "Local Lab",
        server_host: "ts.example.invalid",
        identity_ref: "identity.lab",
        nickname: None,
    })?;
    info!(target: "spike", "inserted bookmark ids: {id_a}, {id_b}");

    repo.touch_connected(id_a, 1_715_000_000)?;
    SettingsRepository::put(&repo, "audio.aec", "true")?;
    SettingsRepository::put(&repo, "audio.ns", "true")?;

    let list = BookmarkRepository::list_ordered(&repo)?;
    println!("\nBookmarks (most-recently-connected first):");
    for b in &list {
        println!(
            "  [{}] {} @ {} (identity_ref={}, last_connected_at={:?})",
            b.id, b.server_name, b.server_host, b.identity_ref, b.last_connected_at
        );
    }

    let aec = SettingsRepository::get(&repo, "audio.aec")?;
    println!("\nSettings.audio.aec = {aec:?}");

    println!("\nOK — schema v{} loaded, repository round-trip verified.", repo.schema_version()?);
    Ok(())
}
