// Copyright (C) 2025 Piers Finlayson <piers@piers.rocks>
//
// MIT License

use embed_resource::{CompilationResult, compile};
use git2::Repository;
use std::path::PathBuf;

fn main() {
    // Minimum macOS deployment target
    println!("cargo:rustc-env=MACOSX_DEPLOYMENT_TARGET=10.13");

    // Re-run build script if build.rs changes
    println!("cargo:rerun-if-changed=build.rs");

    // Write built-time information
    built::write_built_file().expect("Failed to acquire build-time information");

    // Compile Windows resources
    if std::env::var("CARGO_CFG_TARGET_OS").unwrap() == "windows" {
        compile_windows_resources();
    }

    #[cfg(all(windows, target_env = "msvc"))]
    static_vcruntime::metabuild();
}

fn compile_windows_resources() {
    // Create a version string, including git commit if available
    let commit_id = if let Ok(repo) = Repository::open("../..") {
        let head = repo.head().unwrap();
        let commit = head.peel_to_commit().unwrap();
        let commit_id = commit.id().to_string()[..7].to_string();

        let statuses = repo.statuses(None).unwrap();
        let is_dirty = !statuses.is_empty();

        format!(" ({}{})", if is_dirty { "!" } else { "" }, &commit_id,)
    } else {
        println!("cargo:warning=Could not open git repository to get commit ID");
        "".to_string()
    };
    let version = format!("v{}{}", env!("CARGO_PKG_VERSION"), commit_id,);

    // Get absolute path to icon
    let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
    let icon_path = PathBuf::from(manifest_dir)
        .join("..")
        .join("studio")
        .join("assets")
        .join("onerom.ico")
        .display()
        .to_string()
        .replace("\\", "/");

    // Parse Cargo version (e.g. "0.2.1" -> "0,2,1,0")
    let cargo_version = env!("CARGO_PKG_VERSION");
    let parts: Vec<&str> = cargo_version.split('.').collect();
    let file_version = format!(
        "{},{},{},0",
        parts.first().unwrap_or(&"0"),
        parts.get(1).unwrap_or(&"0"),
        parts.get(2).unwrap_or(&"0")
    );

    // Create RC file content
    // - 0809 is English UK, used twice below
    // - FileVersion is auto-generated by embed-resource from Cargo version
    let rc_content = format!(
        r#"1 ICON "{icon_path}"

1 VERSIONINFO
FILEVERSION {file_version}
PRODUCTVERSION {file_version}
{{
  BLOCK "StringFileInfo"
  {{
    BLOCK "080904E4"
    {{
      VALUE "ProductName", "One ROM"
      VALUE "FileDescription", "One ROM CLI - Manage One ROMs"
      VALUE "ProductVersion", "{version}"
      VALUE "OriginalFilename", "onerom.exe"
      VALUE "LegalCopyright", "2026 Piers Finlayson"
      VALUE "CompanyName", "piers.rocks"
    }}
  }}
  BLOCK "VarFileInfo"
  {{
    VALUE "Translation", 0x809, 1252
  }}
}}"#
    );

    let out_dir = std::env::var("OUT_DIR").unwrap();
    let rc_path = format!("{}/resources.rc", out_dir);
    std::fs::write(&rc_path, rc_content).unwrap();

    let result = compile(&rc_path, embed_resource::NONE);
    if result != CompilationResult::Ok {
        panic!("Failed to compile Windows resources {result}");
    }
}
