use clap::Parser;
use std::path::PathBuf;

use crate::color::{parse_hex_color, RgbColor};

#[derive(Debug, Clone, Parser)]
#[command(
    name = "rsimg",
    about = "Generate PNG images with diagonal lines and large centered text",
    version,
    after_help = "Examples:\n  \
        rsimg 200 300 ttt\n  \
        rsimg 200 300 ttt --count 23\n  \
        rsimg 200 300 ttt --color ffffff\n  \
        rsimg 200 300 ttt --count 23 --color ffffff"
)]
struct Cli {
    /// Image width in pixels
    width: u32,

    /// Image height in pixels
    height: u32,

    /// Output filename prefix and text drawn at the center
    name: String,

    /// Number of images to generate (files named {name}_{n}.png when > 1)
    #[arg(long, default_value_t = 1)]
    count: u32,

    /// Background color as 6-digit hex without '#' (e.g. ffffff)
    #[arg(long, value_name = "HEX")]
    color: Option<String>,
}

#[derive(Debug, Clone)]
pub struct Args {
    pub width: u32,
    pub height: u32,
    pub count: u32,
    pub name: String,
    pub color: Option<RgbColor>,
}

pub fn parse_args() -> anyhow::Result<Args> {
    let cli = Cli::parse();

    if cli.width == 0 || cli.height == 0 {
        anyhow::bail!("Width and height must be greater than zero");
    }
    if cli.count == 0 {
        anyhow::bail!("Count must be at least 1");
    }

    let color = match &cli.color {
        Some(hex) => Some(parse_hex_color(hex)?),
        None => None,
    };

    Ok(Args {
        width: cli.width,
        height: cli.height,
        count: cli.count,
        name: cli.name,
        color,
    })
}

pub fn output_path(name: &str, index: u32, count: u32) -> PathBuf {
    if count == 1 {
        PathBuf::from(format!("{name}.png"))
    } else {
        PathBuf::from(format!("{name}_{index}.png"))
    }
}
