use std::path::PathBuf;
use std::process::Command;
use tempfile::TempDir;
use lopdf::Document;
use printpdf::*;

fn create_dummy_pdf(path: &std::path::Path, text: &str) {
    let (doc, page1, layer1) = PdfDocument::new(text, Mm(210.0), Mm(297.0), "Layer 1");
    let current_layer = doc.get_page(page1).get_layer(layer1);
    
    // Just save it
    let file = std::fs::File::create(path).unwrap();
    let mut buf = std::io::BufWriter::new(file);
    doc.save(&mut buf).unwrap();
}

#[test]
fn test_bundle_pdfs_with_rotation() {
    let temp_dir = TempDir::new().unwrap();
    let root = temp_dir.path();
    
    let pdf1 = root.join("doc1.pdf");
    let pdf2 = root.join("doc2.pdf");
    let output = root.join("output.pdf");
    
    create_dummy_pdf(&pdf1, "Doc 1");
    create_dummy_pdf(&pdf2, "Doc 2");
    
    // Use the library directly if possible? 
    // l-tool library exposes commands.
    // We need to use async runtime.
    
    let runtime = tokio::runtime::Runtime::new().unwrap();
    runtime.block_on(async {
        let args = l_tool::commands::pdf::commands::BundleArgs {
            inputs: vec![
                pdf1.to_str().unwrap().to_string(),
                format!("{}:90", pdf2.to_str().unwrap()),
            ],
            dir: None,
            output: output.clone(),
            paper: l_tool::commands::pdf::commands::PaperKind::A4,
            orientation: l_tool::commands::pdf::commands::Orientation::Portrait,
            sort: l_tool::commands::pdf::commands::SortKind::None,
            rotate: None,
        };
        
        l_tool::commands::pdf::bundle::execute(args).unwrap();
    });
    
    assert!(output.exists());
    
    // Verify output with lopdf
    let doc = Document::load(&output).unwrap();
    let pages = doc.get_pages();
    assert_eq!(pages.len(), 2);
    
    // Check rotation of second page (which came from doc2)
    // We need to find which page is which. Order should be preserved.
    // get_pages returns BTreeMap<u32, ObjectId> where key is page number (1-based).
    
    let p1_id = pages.get(&1).unwrap();
    let p2_id = pages.get(&2).unwrap();
    
    let p1 = doc.get_object(*p1_id).unwrap().as_dict().unwrap();
    let p2 = doc.get_object(*p2_id).unwrap().as_dict().unwrap();
    
    // p1 should have no rotation (or 0)
    if let Ok(rot) = p1.get(b"Rotate") {
        assert_eq!(rot.as_i64().unwrap() % 360, 0);
    }
    
    // p2 should have 90 rotation
    let rot = p2.get(b"Rotate").expect("Page 2 should have rotation");
    assert_eq!(rot.as_i64().unwrap(), 90);
}

#[test]
fn test_bundle_rotation_precedence() {
    let temp_dir = TempDir::new().unwrap();
    let root = temp_dir.path();
    
    let pdf1 = root.join("doc1.pdf");
    let pdf2 = root.join("doc2.pdf");
    let output = root.join("output_mixed.pdf");
    
    create_dummy_pdf(&pdf1, "Doc 1");
    create_dummy_pdf(&pdf2, "Doc 2");
    
    let runtime = tokio::runtime::Runtime::new().unwrap();
    runtime.block_on(async {
        let args = l_tool::commands::pdf::commands::BundleArgs {
            inputs: vec![
                // This file should use its own rotation (90)
                format!("{}:90", pdf1.to_str().unwrap()),
                // This file should use global rotation (180)
                pdf2.to_str().unwrap().to_string(),
            ],
            dir: None,
            output: output.clone(),
            paper: l_tool::commands::pdf::commands::PaperKind::A4,
            orientation: l_tool::commands::pdf::commands::Orientation::Portrait,
            sort: l_tool::commands::pdf::commands::SortKind::None,
            rotate: Some(180), // Global rotation
        };
        
        l_tool::commands::pdf::bundle::execute(args).unwrap();
    });
    
    let doc = Document::load(&output).unwrap();
    let pages = doc.get_pages();
    
    // Check Page 1 (Individual override)
    let p1_id = pages.get(&1).unwrap();
    let p1 = doc.get_object(*p1_id).unwrap().as_dict().unwrap();
    let rot1 = p1.get(b"Rotate").expect("Page 1 should have rotation").as_i64().unwrap();
    assert_eq!(rot1, 90, "Individual rotation should take precedence");
    
    // Check Page 2 (Global fallback)
    let p2_id = pages.get(&2).unwrap();
    let p2 = doc.get_object(*p2_id).unwrap().as_dict().unwrap();
    let rot2 = p2.get(b"Rotate").expect("Page 2 should have rotation").as_i64().unwrap();
    assert_eq!(rot2, 180, "Global rotation should apply when individual is missing");
}
