//! Concatenate multiple clips using `FilterGraphBuilder` + `Pipeline`.
//!
//! Available effects:
//!   `video` — concatenate video streams from two clips (no audio)
//!   `audio` — concatenate audio streams from two clips (no video)
//!
//! Both effects require exactly two input files (`--input-a` and `--input-b`).
//!
//! # Usage
//!
//! ```bash
//! cargo run --example clip_concat --features pipeline -- \
//!   --input-a  clip1.mp4  \
//!   --input-b  clip2.mp4  \
//!   --output   joined.mp4 \
//!   --effect   video
//! ```

use std::{
    io::{self, Write as _},
    path::Path,
    process,
};

use avio::{AudioCodec, EncoderConfig, FilterGraphBuilder, Pipeline, Progress, VideoCodec};

fn render_progress(p: &Progress) {
    match p.percent() {
        Some(pct) => {
            let bar_width = 20usize;
            #[allow(
                clippy::cast_possible_truncation,
                clippy::cast_sign_loss,
                clippy::cast_precision_loss
            )]
            let filled = ((pct / 100.0) * bar_width as f64).round() as usize;
            let filled = filled.min(bar_width);
            let bar = "=".repeat(filled) + &" ".repeat(bar_width - filled);
            print!("\r{pct:5.1}%  [{bar}]    ");
        }
        None => {
            print!("\r{} frames    ", p.frames_processed);
        }
    }
    let _ = io::stdout().flush();
}

fn main() {
    let mut args = std::env::args().skip(1);
    let mut input_a = None::<String>;
    let mut input_b = None::<String>;
    let mut output = None::<String>;
    let mut effect = None::<String>;

    while let Some(flag) = args.next() {
        match flag.as_str() {
            "--input-a" | "-i" => input_a = Some(args.next().unwrap_or_default()),
            "--input-b" => input_b = Some(args.next().unwrap_or_default()),
            "--output" | "-o" => output = Some(args.next().unwrap_or_default()),
            "--effect" | "-e" => effect = Some(args.next().unwrap_or_default()),
            other => {
                eprintln!("Unknown flag: {other}");
                process::exit(1);
            }
        }
    }

    let input_a = input_a.unwrap_or_else(|| {
        eprintln!(
            "Usage: clip_concat --input-a <file> --input-b <file> --output <file> \
             --effect video|audio"
        );
        process::exit(1);
    });
    let input_b = input_b.unwrap_or_else(|| {
        eprintln!("--input-b is required");
        process::exit(1);
    });
    let output = output.unwrap_or_else(|| {
        eprintln!("--output is required");
        process::exit(1);
    });
    let effect = effect.unwrap_or_else(|| {
        eprintln!("--effect is required (video|audio)");
        process::exit(1);
    });

    let a_name = Path::new(&input_a)
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or(&input_a);
    let b_name = Path::new(&input_b)
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or(&input_b);
    let out_name = Path::new(&output)
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or(&output);

    // ── Build filter graph ────────────────────────────────────────────────────

    let filter_result = match effect.as_str() {
        "video" => {
            println!("Input A: {a_name}");
            println!("Input B: {b_name}");
            println!("Effect:  concat_video  (2 segments)");
            println!("Output:  {out_name}");
            FilterGraphBuilder::new().concat_video(2).build()
        }
        "audio" => {
            println!("Input A: {a_name}");
            println!("Input B: {b_name}");
            println!("Effect:  concat_audio  (2 segments)");
            println!("Output:  {out_name}");
            FilterGraphBuilder::new().concat_audio(2).build()
        }
        other => {
            eprintln!("Unknown effect '{other}' (try video, audio)");
            process::exit(1);
        }
    };

    let filter = match filter_result {
        Ok(fg) => fg,
        Err(e) => {
            eprintln!("Error building filter graph: {e}");
            process::exit(1);
        }
    };

    println!();

    // ── Assemble pipeline ─────────────────────────────────────────────────────

    let config = EncoderConfig::builder()
        .video_codec(VideoCodec::H264)
        .audio_codec(AudioCodec::Aac)
        .crf(23)
        .build();

    let pipeline = match Pipeline::builder()
        .input(&input_a)
        .input(&input_b)
        .filter(filter)
        .output(&output, config)
        .on_progress(|p: &Progress| {
            render_progress(p);
            true
        })
        .build()
    {
        Ok(p) => p,
        Err(e) => {
            eprintln!("Error: {e}");
            process::exit(1);
        }
    };

    if let Err(e) = pipeline.run() {
        println!();
        eprintln!("Error: {e}");
        process::exit(1);
    }

    println!();

    let size_str = match std::fs::metadata(&output) {
        Ok(m) => {
            #[allow(clippy::cast_precision_loss)]
            let kb = m.len() as f64 / 1024.0;
            if kb < 1024.0 {
                format!("{kb:.0} KB")
            } else {
                format!("{:.1} MB", kb / 1024.0)
            }
        }
        Err(_) => "(unknown size)".to_string(),
    };

    println!("Done. {out_name}  {size_str}");
}
