use std::fs;
use std::path::Path;
use vergen::EmitBuilder;

fn main() -> Result<(), Box<dyn std::error::Error>> {
	// Emit the instructions
	EmitBuilder::builder()
		.git_sha(true)
		.git_commit_timestamp()
		.git_branch()
		.cargo_opt_level()
		.cargo_target_triple()
		.emit()?;

	// Emit build timestamp manually
	println!(
		"cargo:rustc-env=BUILD_TIMESTAMP={}",
		chrono::Utc::now().to_rfc3339()
	);

	// Watch for changes in ops and event modules to trigger client regeneration
	println!("cargo:rerun-if-changed=src/ops");
	println!("cargo:rerun-if-changed=src/infra/event");
	println!("cargo:rerun-if-changed=src/domain");

	// Generate Swift API code automatically
	generate_swift_api_code()?;

	Ok(())
}

/// Generate Swift API code and write it to the Swift client package
fn generate_swift_api_code() -> Result<(), Box<dyn std::error::Error>> {
	// Import the type extraction functions
	// Note: We need to use a different approach since we can't import from the main crate
	// We'll use the existing generate_swift_types binary as a reference

	let swift_client_path = Path::new("packages/swift-client/Sources/SpacedriveClient");
	let api_file_path = swift_client_path.join("SpacedriveAPI.swift");

	// Check if the Swift client directory exists
	if !swift_client_path.exists() {
		println!("cargo:warning=Swift client directory not found, skipping API generation");
		return Ok(());
	}

	// Generate the API code using the existing binary
	let output = std::process::Command::new("cargo")
		.args(["run", "--bin", "generate_swift_types", "--quiet"])
		.output()?;

	if !output.status.success() {
		let error_msg = String::from_utf8_lossy(&output.stderr);
		println!(
			"cargo:warning=Failed to generate Swift types: {}",
			error_msg
		);
		return Ok(());
	}

	// Read the generated types file to extract the API structure
	let types_file_path = swift_client_path.join("SpacedriveTypes.swift");
	if !types_file_path.exists() {
		println!("cargo:warning=Types.swift not found, skipping API generation");
		return Ok(());
	}

	// For now, we'll create a placeholder API file
	// The actual implementation will be done by modifying the generate_swift_types binary
	let api_code = generate_placeholder_api_code();

	// Write the API code to the Swift client
	fs::write(&api_file_path, api_code)?;

	println!(
		"cargo:rerun-if-changed=packages/swift-client/Sources/SpacedriveClient/SpacedriveAPI.swift"
	);

	Ok(())
}

/// Generate placeholder API code (will be replaced by actual generation)
fn generate_placeholder_api_code() -> String {
	r#"// MARK: - Generated API Code
// This file is automatically generated by the Rust build process
// Do not edit manually - changes will be overwritten

import Foundation

// MARK: - API Namespace Extensions
// These extensions will be automatically generated based on the Rust API structure

extension SpacedriveClient {
    // API methods will be generated here automatically
}
"#
	.to_string()
}
