// SPDX-FileCopyrightText: 2025 Hong Minhee <https://hongminhee.org/>
// SPDX-License-Identifier: GPL-3.0-or-later
//! Build script for Hongdown.
//!
//! This script reads the proper-nouns.tsv file and generates Rust constants
//! for use in the sentence case converter.

use std::env;
use std::fs;
use std::io::Write;
use std::path::Path;

fn main() {
    // Read the proper-nouns.tsv file
    let tsv_path = "data/proper-nouns.tsv";
    println!("cargo:rerun-if-changed={}", tsv_path);

    let content = fs::read_to_string(tsv_path).expect("Failed to read proper-nouns.tsv");

    // Parse the TSV file
    let mut proper_nouns = Vec::new();

    for line in content.lines() {
        let line = line.trim();

        // Skip empty lines and comments
        if line.is_empty() || line.starts_with('#') {
            continue;
        }

        // Normalize apostrophes to curly form for consistent matching
        // This matches the behavior of normalize_quotes() in the serializer
        let canonical = line.replace('\'', "\u{2019}");
        let lowercase_key = canonical.to_lowercase();

        proper_nouns.push((canonical, lowercase_key));
    }

    // Generate Rust code
    let out_dir = env::var("OUT_DIR").expect("OUT_DIR not set");
    let dest_path = Path::new(&out_dir).join("proper_nouns_generated.rs");
    let mut f = fs::File::create(dest_path).expect("Failed to create output file");

    writeln!(f, "// Generated by build.rs - DO NOT EDIT").unwrap();
    writeln!(f).unwrap();
    writeln!(f, "/// Built-in proper nouns for sentence case conversion.").unwrap();
    writeln!(
        f,
        "/// Each tuple contains (canonical_form, lowercase_search_key)."
    )
    .unwrap();
    writeln!(f, "pub const PROPER_NOUNS: &[(&str, &str)] = &[").unwrap();

    for (canonical, lowercase_key) in proper_nouns {
        writeln!(f, "    (\"{}\", \"{}\"),", canonical, lowercase_key).unwrap();
    }

    writeln!(f, "];").unwrap();
}
