use anyhow::{anyhow, Result};
use headless_chrome::{Browser, LaunchOptions};
use headless_chrome::types::PrintToPdfOptions;
use std::path::Path;

pub fn generate_pdf(html_content: &str, template_dir: &Path, output_path: &Path) -> Result<()> {
    let css_path = template_dir.join("style.css");
    if !css_path.exists() {
        return Err(anyhow!("CSS file not found at {}", css_path.display()));
    }
    
    let css_content = std::fs::read_to_string(&css_path)?;
    
    let full_html = format!(
        r#"<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
    {}
    </style>
</head>
<body>
{}
</body>
</html>"#,
        css_content,
        html_content.replace(r#"<link rel="stylesheet" href="style.css">"#, "")
    );
    
    let launch_options = LaunchOptions::default_builder()
        .path(Some("/Applications/Brave Browser.app/Contents/MacOS/Brave Browser".into()))
        .build()
        .expect("Couldn't find Brave Browser");
    let browser = Browser::new(launch_options)?;
    let tab = browser.new_tab()?;
    
    tab.navigate_to(&format!("data:text/html,{}", urlencoding::encode(&full_html)))?;
    tab.wait_until_navigated()?;
    
    let pdf_options = PrintToPdfOptions {
        landscape: Some(true),
        display_header_footer: Some(false),
        print_background: Some(true),
        scale: Some(1.0),
        paper_width: Some(11.0),
        paper_height: Some(8.5),
        margin_top: Some(0.5),
        margin_bottom: Some(0.5),
        margin_left: Some(0.5),
        margin_right: Some(0.5),
        page_ranges: None,
        ignore_invalid_page_ranges: None,
        header_template: None,
        footer_template: None,
        prefer_css_page_size: Some(true),
        transfer_mode: None,
        generate_tagged_pdf: None,
        generate_document_outline: None,
    };
    
    let pdf_data = tab.print_to_pdf(Some(pdf_options))?;
    
    std::fs::write(output_path, pdf_data)?;
    
    Ok(())
}