use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

pub fn compile(
    tex: &str,
    output_dir: &Path,
) -> Result<PathBuf, Box<dyn std::error::Error>> {

    // create a temp directory like /tmp/txt2tex-a3f8k2/
    // it auto-deletes when tmp_dir is dropped at end of this function
    let tmp_dir  = tempfile::tempdir()?;
    let tex_path = tmp_dir.path().join("resume.tex");

    // write the LaTeX source to the temp file
    fs::write(&tex_path, tex)?;

    // check tectonic is installed before trying to use it
    // .output() returns Err if the program does not exist
    // .is_err() returns true if it returned Err
    if Command::new("tectonic").arg("--version").output().is_err() {
        return Err("\
tectonic not found. Install it first:

  macOS   →  brew install tectonic
  Linux   →  cargo install tectonic
  Windows →  https://tectonic-typesetting.github.io/en-US/install.html
".into());
    }

    // run: tectonic /tmp/.../resume.tex
    // .current_dir() sets the working directory for the command
    // .output()      runs it and captures stdout + stderr
    let result = Command::new("tectonic")
        .arg(&tex_path)
        .current_dir(tmp_dir.path())
        .output()?;

    if !result.status.success() {
        // result.stderr is Vec<u8> (raw bytes)
        // from_utf8_lossy converts to a readable string like if valid then ok,else ?
        let err = String::from_utf8_lossy(&result.stderr);
        return Err(format!("LaTeX compilation failed:\n{}", err).into());
    }

    // tectonic creates resume.pdf in the same directory as resume.tex
    let pdf_tmp = tmp_dir.path().join("resume.pdf");

    if !pdf_tmp.exists() {
        return Err("Tectonic ran but no PDF was created. Check your LaTeX.".into());
    }

    // copy PDF from temp dir to the output folder
    let pdf_out = output_dir.join("resume.pdf");
    fs::copy(&pdf_tmp, &pdf_out)?;

    // tmp_dir is dropped here(RAII)

    Ok(pdf_out)
}
