//! 命令行参数解析。

use std::path::PathBuf;

pub enum Command {
    Run {
        target: PathBuf,
        debug: bool,
    },
    New {
        dir: PathBuf,
    },
    Status {
        dir: PathBuf,
        json: bool,
    },
    Build {
        dir: PathBuf,
        output: Option<PathBuf>,
        plain: bool,
    },
    Info {
        file: PathBuf,
    },
    Edit {
        dir: PathBuf,
    },
    Help,
    Version,
}

pub struct Args {
    pub command: Command,
}

impl Args {
    pub fn parse() -> Self {
        let args: Vec<String> = std::env::args().skip(1).collect();
        if args.is_empty() {
            return Args {
                command: Command::Run {
                    target: PathBuf::from("."),
                    debug: false,
                },
            };
        }

        let mut rest: Vec<String> = Vec::new();
        let mut debug = false;
        let mut json = false;
        let mut plain = false;
        let mut output = None;

        for arg in &args[1..] {
            match arg.as_str() {
                "--debug" => debug = true,
                "--json" => json = true,
                "--plain" => plain = true,
                _ => rest.push(arg.clone()),
            }
        }

        let command = match args[0].as_str() {
            "-h" | "--help" | "help" => Command::Help,
            "-V" | "--version" | "version" => Command::Version,
            "new" => match rest.first() {
                Some(name) => Command::New {
                    dir: expand_path(name),
                },
                None => Command::Help,
            },
            "status" | "check" => Command::Status {
                dir: rest.first().map(|s| expand_path(s)).unwrap_or_default(),
                json,
            },
            "build" | "pack" => {
                let dir = match rest.first() {
                    Some(first) => expand_path(first),
                    None => PathBuf::from("."),
                };
                if rest.len() > 1 {
                    output = Some(expand_path(&rest[1]));
                }
                Command::Build { dir, output, plain }
            }
            "edit" => Command::Edit {
                dir: rest.first().map(|s| expand_path(s)).unwrap_or_default(),
            },
            "info" => match rest.first() {
                Some(file) => Command::Info {
                    file: expand_path(file),
                },
                None => Command::Help,
            },
            "run" => Command::Run {
                target: rest
                    .first()
                    .map(|s| expand_path(s))
                    .unwrap_or_else(|| PathBuf::from(".")),
                debug,
            },
            other => {
                let target = expand_path(other);
                Command::Run { target, debug }
            }
        };

        Args { command }
    }

    pub fn print_help() {
        println!("ngal-gui - Galgame 图形引擎");
        println!();
        println!("用法:");
        println!("  ngal-gui                       在当前目录运行游戏");
        println!("  ngal-gui <目录>                运行指定目录的项目");
        println!("  ngal-gui <文件.ngal>           直接运行打包好的游戏");
        println!("  ngal-gui <文件.ngal> --debug   运行打包游戏并显示信息");
        println!("  ngal-gui new <目录>            创建新项目");
        println!("  ngal-gui status [目录]         检查剧情缺失的资源");
        println!("  ngal-gui status [目录] --json  以 JSON 输出检查结果");
        println!("  ngal-gui build [目录] [输出]   打包为 .ngal");
        println!("  ngal-gui build [目录] [输出] --plain  打包为可直接解压的 zip");
        println!("  ngal-gui info <文件.ngal>      查看打包文件信息");
        println!("  ngal-gui edit [目录]           打开内容编辑器(文本 / 拖拽模块)");
        println!("  ngal-gui help                  显示此帮助");
        println!("  ngal-gui version               显示版本");
    }

    pub fn print_version() {
        println!("ngal-gui version {}", env!("CARGO_PKG_VERSION"));
    }
}

pub fn expand_path(path: &str) -> PathBuf {
    if path == "~" || path.starts_with("~/") {
        let home = std::env::var("HOME")
            .or_else(|_| std::env::var("USERPROFILE"))
            .ok();
        if let Some(home) = home {
            let rest = if path == "~" { "" } else { &path[2..] };
            return PathBuf::from(home).join(rest);
        }
    }
    PathBuf::from(path)
}