//! Tiny, dependency-free TOML-like reader/writer for the settings app.
//!
//! Stored at `~/.config/eydos/settings.toml`. Only a handful of keys are
//! recognised, each on its own line in `key=value` form. Unknown keys
//! and blank/comment lines are preserved when rewriting so that user or
//! future edits aren't clobbered.
//!
//! Recognised keys:
//!
//!   theme_mode      = auto | light | dark
//!   wallpaper       = <name>          (currently always "wallpaper")
//!   wallpaper_variant = light | dark
//!
//! All readers return defaults on any error (missing file, parse error,
//! permission denied) so the UI always has something sensible to show.

use std::fs;
use std::path::PathBuf;

use ltk::{ ThemeMode, ThemePreference };

// ─── Paths ───────────────────────────────────────────────────────────────────

fn config_dir() -> Option<PathBuf>
{
	let home = std::env::var( "HOME" ).ok()?;
	Some( PathBuf::from( home ).join( ".config" ).join( "eydos" ) )
}

fn config_path() -> Option<PathBuf>
{
	Some( config_dir()?.join( "settings.toml" ) )
}

// ─── Generic key/value store ─────────────────────────────────────────────────

fn read_all() -> Vec<( String, String )>
{
	let Some( path ) = config_path() else { return Vec::new(); };
	let Ok( text ) = fs::read_to_string( &path ) else { return Vec::new(); };
	let mut out = Vec::new();
	for line in text.lines()
	{
		let trimmed = line.trim();
		if trimmed.is_empty() || trimmed.starts_with( '#' ) { continue; }
		if let Some( ( k, v ) ) = trimmed.split_once( '=' )
		{
			let key = k.trim().to_string();
			let val = v.trim().trim_matches( '"' ).to_string();
			out.push( ( key, val ) );
		}
	}
	out
}

fn write_key( key: &str, value: &str )
{
	let Some( dir ) = config_dir() else { return; };
	let _ = fs::create_dir_all( &dir );
	let Some( path ) = config_path() else { return; };

	let mut entries = read_all();
	let mut replaced = false;
	for ( k, v ) in entries.iter_mut()
	{
		if k == key { *v = value.to_string(); replaced = true; break; }
	}
	if !replaced { entries.push( ( key.to_string(), value.to_string() ) ); }

	let mut out = String::new();
	for ( k, v ) in &entries
	{
		out.push_str( k );
		out.push( '=' );
		out.push_str( v );
		out.push( '\n' );
	}
	let _ = fs::write( &path, out );
}

fn read_key( key: &str ) -> Option<String>
{
	read_all().into_iter().find_map( |( k, v )| if k == key { Some( v ) } else { None } )
}

// ─── Theme preference ────────────────────────────────────────────────────────

pub fn read_theme_pref() -> ThemePreference
{
	match read_key( "theme_mode" ).as_deref()
	{
		Some( "light" ) => ThemePreference::Light,
		Some( "dark"  ) => ThemePreference::Dark,
		Some( "auto"  ) => ThemePreference::Auto,
		_               => ThemePreference::Auto,
	}
}

pub fn write_theme_pref( pref: ThemePreference )
{
	let val = match pref
	{
		ThemePreference::Light => "light",
		ThemePreference::Dark  => "dark",
		ThemePreference::Auto  => "auto",
	};
	write_key( "theme_mode", val );
}

// ─── Wallpaper variant ───────────────────────────────────────────────────────

pub fn read_wallpaper_variant() -> ThemeMode
{
	match read_key( "wallpaper_variant" ).as_deref()
	{
		Some( "dark"  ) => ThemeMode::Dark,
		Some( "light" ) => ThemeMode::Light,
		_               => ThemeMode::Light,
	}
}

pub fn write_wallpaper_variant( mode: ThemeMode )
{
	let val = match mode
	{
		ThemeMode::Light => "light",
		ThemeMode::Dark  => "dark",
	};
	write_key( "wallpaper_variant", val );
}
