extern crate alloc;

use burn::module::{Initializer, Param};
use burn::prelude::*;

use burn_store::{ModuleSnapshot, PytorchStore};
use std::path::Path;
use std::time::Instant;

#[cfg(feature = "wgpu")]
pub type MyBackend = burn::backend::Wgpu;

#[cfg(feature = "ndarray")]
pub type MyBackend = burn::backend::NdArray<f32>;

#[cfg(feature = "tch")]
pub type MyBackend = burn::backend::LibTorch<f32>;

#[cfg(feature = "metal")]
pub type MyBackend = burn::backend::Metal;

// Import model info generated by build.rs (includes the yolo_model module)
include!(concat!(env!("OUT_DIR"), "/model_info.rs"));

// Use the yolo_model module from model_info.rs
use yolo_model::Model;

#[derive(Debug, Module)]
struct TestData<B: Backend> {
    input: Param<Tensor<B, 4>>,
    output: Param<Tensor<B, 3>>,
}

impl<B: Backend> TestData<B> {
    fn new(device: &B::Device) -> Self {
        // YOLO: input 640x640, output [1, 84, 8400]
        Self {
            input: Initializer::Zeros.init([1, 3, 640, 640], device),
            output: Initializer::Zeros.init([1, 84, 8400], device),
        }
    }
}

fn get_model_display_name(model_name: &str) -> &str {
    match model_name {
        "yolov5s" => "YOLOv5s",
        "yolov8n" => "YOLOv8n",
        "yolov8s" => "YOLOv8s",
        "yolov10n" => "YOLOv10n",
        "yolo11x" => "YOLO11x",
        "yolo12x" => "YOLO12x",
        _ => model_name,
    }
}

fn main() {
    // MODEL_NAME is set at build time from YOLO_MODEL env var
    let model_name = MODEL_NAME;
    let display_name = get_model_display_name(model_name);

    println!("========================================");
    println!("{} Burn Model Test", display_name);
    println!("========================================\n");

    // Check if artifacts exist
    let artifacts_dir = Path::new("artifacts");
    if !artifacts_dir.exists() {
        eprintln!("Error: artifacts directory not found!");
        eprintln!("Please run get_model.py first to download the model and test data.");
        eprintln!("Example: uv run get_model.py --model {}", model_name);
        std::process::exit(1);
    }

    // Check if model files exist for this specific model
    let model_file = artifacts_dir.join(format!("{}_opset16.onnx", model_name));
    let test_data_file = artifacts_dir.join(format!("{}_test_data.pt", model_name));

    if !model_file.exists() || !test_data_file.exists() {
        eprintln!("Error: Model files not found for {}!", display_name);
        eprintln!("Please run: uv run get_model.py --model {}", model_name);
        eprintln!();
        eprintln!("Available models:");
        eprintln!("  - yolov5s");
        eprintln!("  - yolov8n");
        eprintln!("  - yolov8s");
        eprintln!("  - yolov10n");
        eprintln!("  - yolo11x");
        eprintln!("  - yolo12x");
        std::process::exit(1);
    }

    // Initialize the model (without weights for now)
    println!("Initializing {} model...", display_name);
    let start = Instant::now();
    let device = Default::default();
    let model: Model<MyBackend> = Model::default();
    let init_time = start.elapsed();
    println!("  Model initialized in {:.2?}", init_time);

    // Save model structure to file
    let model_txt_path = artifacts_dir.join(format!("{}_model.txt", model_name));
    println!(
        "\nSaving model structure to {}...",
        model_txt_path.display()
    );
    let model_str = format!("{}", model);
    std::fs::write(&model_txt_path, &model_str).expect("Failed to write model structure to file");
    println!("  Model structure saved");

    // Load test data from PyTorch file
    println!("\nLoading test data from {}...", test_data_file.display());
    let start = Instant::now();
    let mut test_data = TestData::<MyBackend>::new(&device);
    let mut store = PytorchStore::from_file(&test_data_file);
    test_data.load_from(&mut store).expect("Failed to load test data");
    let load_time = start.elapsed();
    println!("  Data loaded in {:.2?}", load_time);

    // Get the input tensor from test data
    let input = test_data.input.val();
    let input_shape = input.shape();
    println!("  Loaded input tensor with shape: {:?}", input_shape.dims);

    // Get the reference output from test data
    let reference_output = test_data.output.val();
    let reference_shape = reference_output.shape();
    println!(
        "  Loaded reference output with shape: {:?}",
        reference_shape.dims
    );

    // Run inference with the loaded input
    println!("\nRunning model inference with test input...");
    let start = Instant::now();
    let output = model.forward(input);
    let inference_time = start.elapsed();
    println!("  Inference completed in {:.2?}", inference_time);

    // Display output shape
    let shape = output.shape();
    println!("\n  Model output shape: {:?}", shape.dims);

    // Verify expected output shape (most YOLO models use [1, 84, 8400])
    let expected_shape = [1, 84, 8400];
    if shape.dims == expected_shape {
        println!("  ✓ Output shape matches expected: {:?}", expected_shape);
    } else {
        println!(
            "  ⚠ Note: Shape is {:?} (expected {:?} for most YOLO models)",
            shape.dims, expected_shape
        );
    }

    // Compare outputs
    println!("\nComparing model output with reference data...");

    // Check if outputs are close
    if output
        .clone()
        .all_close(reference_output.clone(), Some(1e-4), Some(1e-4))
    {
        println!("  ✓ Model output matches reference data within tolerance (1e-4)!");
    } else {
        println!("  ⚠ Model output differs from reference data!");

        // Calculate and display the difference statistics
        let diff = output.clone() - reference_output.clone();
        let abs_diff = diff.abs();
        let max_diff = abs_diff.clone().max().into_scalar();
        let mean_diff = abs_diff.mean().into_scalar();

        println!("  Maximum absolute difference: {:.6}", max_diff);
        println!("  Mean absolute difference: {:.6}", mean_diff);

        // Show some sample values for debugging
        println!("\n  Sample values comparison (first 5 elements):");
        let output_flat = output.clone().flatten::<1>(0, 2);
        let reference_flat = reference_output.clone().flatten::<1>(0, 2);

        for i in 0..5.min(output_flat.dims()[0]) {
            let model_val: f32 = output_flat.clone().slice(s![i..i + 1]).into_scalar();
            let ref_val: f32 = reference_flat.clone().slice(s![i..i + 1]).into_scalar();
            println!(
                "    [{}] Model: {:.6}, Reference: {:.6}, Diff: {:.6}",
                i,
                model_val,
                ref_val,
                (model_val - ref_val).abs()
            );
        }
    }

    println!("\n========================================");
    println!("Model test completed!");
    println!("========================================");
}
