use heck::ToSnakeCase;

use crate::complete::CompleteOptions;

pub fn complete_nu(opts: &CompleteOptions) -> String {
    let usage_bin = &opts.usage_bin;
    let bin = &opts.bin;
    let bin_snake = bin.to_snake_case();
    let spec_variable = if let Some(cache_key) = &opts.cache_key {
        format!("_usage_spec_{bin_snake}_{}", cache_key.to_snake_case())
    } else {
        format!("_usage_spec_{bin_snake}")
    };

    let generated_comment = if let Some(source_file) = &opts.source_file {
        format!("# @generated by usage-cli from {source_file}")
    } else {
        "# @generated by usage-cli from usage spec".to_string()
    };
    let mut out = vec![
        generated_comment,
        format!("module _{bin_snake}_completions {{"),
    ];

    if let Some(spec) = &opts.spec {
        out.push(format!("    const {spec_variable} = r##'{spec}'##"));
    }

    // The cache filename is version-keyed and the cache dir is now persistent
    // (unlike the reboot-cleared temp dir), so old versions would accumulate
    // forever. On a cache miss, reap this bin's spec files not regenerated in
    // the last 30 days. Age-based (not "delete all other versions") so that
    // running two versions of the same tool concurrently doesn't thrash — each
    // live version's spec stays recent and survives.
    let prune_stale = format!(
        r#"glob ($spec_dir | path join "usage__usage_spec_{bin_snake}_*.spec") | each {{|f| if ((ls $f | get 0.modified) < ((date now) - 30day)) {{ rm --force $f }} }} | ignore"#
    );

    // Build logic to write spec directly to file without storing in shell variables
    let file_write_logic = if let Some(usage_cmd) = &opts.usage_cmd {
        if opts.cache_key.is_some() {
            format!(
                r#"if not ($spec_file | path exists) {{
            {prune_stale}
            ^{usage_cmd} | collect | save $spec_file
        }}"#
            )
        } else {
            format!(r#"^{usage_cmd} | collect | save -f $spec_file"#)
        }
    } else if let Some(_spec) = &opts.spec {
        if opts.cache_key.is_some() {
            format!(
                r#"if not ($spec_file | path exists) {{
            {prune_stale}
            ${spec_variable} | save $spec_file
        }}"#
            )
        } else {
            format!(r#"${spec_variable} | save -f $spec_file"#)
        }
    } else {
        String::new()
    };

    out.push(
        format!(
            r#"    def {bin_snake}_completer [spans: list<string>] {{
        let spec_dir = ($env.XDG_CACHE_HOME? | default ($nu.home-dir? | default $nu.home-path? | path join ".cache") | path join "usage")
        if not ($spec_dir | path exists) {{
            mkdir $spec_dir
            if $nu.os-info.family != "windows" {{ ^chmod 0700 $spec_dir }}
        }}
        let spec_file = ($spec_dir | path join $"usage_{spec_variable}.spec")
        {file_write_logic}

        (^{usage_bin} complete-word -f $spec_file --shell nu -- ...$spans)
        | lines
        | each {{|it| $it | split column "\t" | rename value description | into record }}
    }}

    @complete {bin_snake}_completer
    export extern {bin} []
}}
"#
        )
        .to_string(),
    );

    out.push(format!(
        r#"
# if "{usage_bin}" is not installed show an error
if (which {usage_bin} | is-empty) {{
    return (error make {{
        msg: "Error: {usage_bin} CLI not found. This is required for completions to work in {bin}.",
        help: "See https://usage.jdx.dev for more information."
    }})
}}
use _{bin_snake}_completions *"#
    ));

    out.join("\n")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test::SPEC_KITCHEN_SINK;
    use insta::assert_snapshot;

    #[test]
    fn test_complete_nu() {
        assert_snapshot!(complete_nu(&CompleteOptions {
            usage_bin: "usage".to_string(),
            shell: "nu".to_string(),
            bin: "mycli".to_string(),
            cache_key: None,
            spec: None,
            usage_cmd: Some("mycli complete --usage".to_string()),
            source_file: None,
        }));
        assert_snapshot!(complete_nu(&CompleteOptions {
            usage_bin: "usage".to_string(),
            shell: "nu".to_string(),
            bin: "mycli".to_string(),
            cache_key: Some("1.2.3".to_string()),
            spec: None,
            usage_cmd: Some("mycli complete --usage".to_string()),
            source_file: None,
        }));
        assert_snapshot!(complete_nu(&CompleteOptions {
            usage_bin: "usage".to_string(),
            shell: "nu".to_string(),
            bin: "mycli".to_string(),
            cache_key: None,
            spec: Some(SPEC_KITCHEN_SINK.clone()),
            usage_cmd: None,
            source_file: None,
        }));
    }
}
