//! Tiny argv parser for eydos-calls.
//!
//! Same minimal surface as the installer: `--windowsize WxH` and
//! `--help`. We deliberately avoid pulling in a CLI crate — the binary
//! ships as part of the phone shell and the flag set is small enough to
//! hand-roll.

const USAGE: &str = "\
Usage: eydos-calls [OPTIONS]

Options:
  --windowsize WxH    Open a centred window of the given pixel size
                      (e.g. --windowsize 480x960). Defaults to fullscreen.
  -h, --help          Print this help and exit.
";

pub struct Cli
{
	pub window_size: Option<( u32, u32 )>,
}

pub fn parse() -> Cli
{
	let mut window_size: Option<( u32, u32 )> = None;
	let mut args = std::env::args().skip( 1 );

	while let Some( arg ) = args.next()
	{
		match arg.as_str()
		{
			"-h" | "--help" =>
			{
				print!( "{}", USAGE );
				std::process::exit( 0 );
			}
			"--windowsize" =>
			{
				let value = args.next().unwrap_or_else( ||
				{
					eprintln!( "error: --windowsize expects a value like 480x960" );
					std::process::exit( 2 );
				} );
				window_size = Some( parse_size( &value ) );
			}
			other if other.starts_with( "--windowsize=" ) =>
			{
				let value = &other[ "--windowsize=".len().. ];
				window_size = Some( parse_size( value ) );
			}
			other =>
			{
				eprintln!( "error: unknown argument {:?}", other );
				eprint!( "{}", USAGE );
				std::process::exit( 2 );
			}
		}
	}

	Cli { window_size }
}

fn parse_size( s: &str ) -> ( u32, u32 )
{
	let parts: Vec<&str> = s.split( |c| c == 'x' || c == 'X' || c == '*' ).collect();
	if parts.len() != 2
	{
		eprintln!( "error: --windowsize must be WxH (got {:?})", s );
		std::process::exit( 2 );
	}
	let w: u32 = parts[ 0 ].trim().parse().unwrap_or_else( |_|
	{
		eprintln!( "error: --windowsize: bad width {:?}", parts[ 0 ] );
		std::process::exit( 2 );
	} );
	let h: u32 = parts[ 1 ].trim().parse().unwrap_or_else( |_|
	{
		eprintln!( "error: --windowsize: bad height {:?}", parts[ 1 ] );
		std::process::exit( 2 );
	} );
	if w == 0 || h == 0
	{
		eprintln!( "error: --windowsize must be positive, got {}x{}", w, h );
		std::process::exit( 2 );
	}
	( w, h )
}
