//! build.rs
//!
//! Uses the `mediatypes` crate's `all_types::all()` function to get every
//! known MIME type, then emits a compile-time `phf::Set<&str>` plus a
//! `KNOWN_MIME_COUNT` constant into `$OUT_DIR/mime_set.rs`.

// Build scripts are inherently panicky — they must fail loudly on errors.
#![allow(
    clippy::expect_used,
    clippy::unwrap_used,
    clippy::panic,
    clippy::arithmetic_side_effects
)]

use std::{env, fs, io::Write as _, path::PathBuf};

fn main() {
    // Re-run only when build script or lock file changes.
    println!("cargo:rerun-if-changed=src/build.rs");
    println!("cargo:rerun-if-changed=Cargo.lock");

    // Use the mediatypes crate directly — no more fragile source parsing.
    let mut mime_types: Vec<&str> = mediatypes::all_types::all();
    mime_types.sort_unstable();
    mime_types.dedup();

    let count = mime_types.len();
    eprintln!("build.rs: found {count} MIME type constants in mediatypes");

    let out_dir = env::var("OUT_DIR").expect("OUT_DIR not set");
    let out_path = PathBuf::from(&out_dir).join("mime_set.rs");
    let mut file = fs::File::create(&out_path)
        .unwrap_or_else(|e| panic!("cannot create {}: {e}", out_path.display())); // rust-doctor-disable-line

    // Build phf::Set
    let mut builder = phf_codegen::Set::new();
    for mime in &mime_types {
        builder.entry(*mime);
    }

    writeln!(
        file,
        "/// All known MIME types from the `mediatypes` crate.\n\
         pub static KNOWN_MIME_TYPES: phf::Set<&str> = {};\n\
         /// Number of MIME type constants in the generated set.\n\
         pub const KNOWN_MIME_COUNT: usize = {count};",
        builder.build(),
    )
    .expect("write mime_set.rs failed");
}
