use sonic_bridge::config::SonicConfig;
use sonic_bridge::pipeline::SonicPipeline;
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;

fn main() {
    let args: Vec<String> = env::args().collect();

    if args.len() < 2 {
        print_usage();
        return;
    }

    let mut config_path = None;
    let mut use_onset = false;
    let mut use_quiet = false;
    let mut clean_args = Vec::new();

    let mut i = 1;
    while i < args.len() {
        if args[i] == "--config" && i + 1 < args.len() {
            config_path = Some(args[i + 1].clone());
            i += 2;
        } else if args[i] == "--onset" {
            use_onset = true;
            i += 1;
        } else if args[i] == "--quiet" || args[i] == "-q" {
            use_quiet = true;
            i += 1;
        } else {
            clean_args.push(args[i].clone());
            i += 1;
        }
    }

    if clean_args.is_empty() {
        print_usage();
        return;
    }

    // Load SonicConfig
    let mut config = if let Some(ref path_str) = config_path {
        SonicConfig::load_from_file(Path::new(path_str)).unwrap_or_else(|e| {
            eprintln!(
                "[!] Warning: Failed to load config from {}: {}. Falling back to default.",
                path_str, e
            );
            SonicConfig::default()
        })
    } else {
        SonicConfig::load_or_default()
    };

    // Command-line flag override
    if use_onset {
        config.onset_mode = true;
    }
    if use_quiet {
        config.quiet_mode = true;
    }

    if clean_args.len() == 1 {
        // 单音轨审美分析模式
        let audio_path = Path::new(&clean_args[0]);
        let is_onset_active = config.onset_mode;
        println!(
            "[*] Analyzing single track: {} (onset mode: {}, step size: {:.1}s) ...",
            audio_path.display(),
            is_onset_active,
            config.step_size
        );

        match SonicPipeline::process_single(audio_path, &config) {
            Ok((meta, segs)) => {
                let mut report = Vec::new();
                report.push("# SonicBridge: LLM-Readable Music Descriptor (LRMD)\n".to_string());
                report.push("> [!NOTE]".to_string());
                report.push("> This is a physical-to-semantic acoustic report generated by SonicBridge. Pure-text LLMs can 'listen to' and 'appreciate' this track via this spatiotemporal matrix.\n".to_string());

                report.push("## 1. Global Acoustic & Musicological Metadata".to_string());
                report.push(format!("- **Filename**: `{}`", meta.filename));
                report.push(format!(
                    "- **Duration**: `{:.2} seconds`",
                    meta.duration_seconds
                ));
                report.push(format!(
                    "- **Tempo (BPM)**: `{:.1} BPM` ({})",
                    meta.estimated_bpm, meta.tempo_feeling
                ));
                report.push(format!(
                    "- **Estimated Key**: `{}`\n",
                    meta.estimated_global_key
                ));

                let interval_header = if is_onset_active {
                    "## 2. Spatiotemporal Track Analysis (Adaptive Onset Intervals)"
                } else {
                    &format!(
                        "## 2. Spatiotemporal Track Analysis ({:.1}-Second Intervals)",
                        config.step_size
                    )
                };
                report.push(interval_header.to_string());
                report.push("| Timeline | Chord | Dynamic Intensity | Timbral Brightness | Rhythmic & Transient Activity |".to_string());
                report.push("| :--- | :--- | :--- | :--- | :--- |".to_string());

                for seg in &segs {
                    report.push(format!(
                        "| **{}** | `{}` | {} | {} | {} |",
                        seg.time_range,
                        seg.chord,
                        seg.dynamic_level,
                        seg.timbre_brightness,
                        seg.rhythm_activity
                    ));
                }

                let report_text = report.join("\n");

                // 保存到本地
                let out_path = format!("{}.lrmd.md", clean_args[0]);
                if let Ok(mut file) = File::create(&out_path) {
                    let _ = file.write_all(report_text.as_bytes());
                    println!(
                        "[+] LRMD report successfully generated and saved to: {}",
                        out_path
                    );
                }

                if !config.quiet_mode {
                    println!("\n=== GENERATED LRMD REPORT PREVIEW ===");
                    println!("{}", report_text);
                }
            }
            Err(e) => {
                eprintln!("[-] Error processing audio track: {}", e);
            }
        }
    } else if clean_args.len() == 2 {
        // 双音轨比对模式
        let path_a = Path::new(&clean_args[0]);
        let path_b = Path::new(&clean_args[1]);
        println!(
            "[*] Running DTW Comparative Analysis:\n  - Track A: {}\n  - Track B: {}",
            path_a.display(),
            path_b.display()
        );

        match SonicPipeline::process_comparative(path_a, path_b) {
            Ok(report_text) => {
                let out_path = format!(
                    "{}_vs_{}.lrmd.md",
                    path_a.file_stem().unwrap().to_str().unwrap(),
                    path_b.file_stem().unwrap().to_str().unwrap()
                );
                if let Ok(mut file) = File::create(&out_path) {
                    let _ = file.write_all(report_text.as_bytes());
                    println!(
                        "[+] Comparative LRMD report generated and saved to: {}",
                        out_path
                    );
                }

                println!("\n=== COMPARATIVE REPORT PREVIEW ===");
                println!("{}", report_text);
            }
            Err(e) => {
                eprintln!("[-] Error running comparative alignment: {}", e);
            }
        }
    } else {
        print_usage();
    }
}

fn print_usage() {
    println!("SonicBridge CLI - LLM-Readable Acoustic Transformer");
    println!("Usage:");
    println!(
        "  1. Single track analysis:      sonic-bridge <path_to_audio> [--onset] [--quiet] [--config <path>]"
    );
    println!("  2. Comparative version analysis: sonic-bridge <path_to_track_A> <path_to_track_B>");
}
