//! Example: call the exported library API and sign an image.

use std::env;

use anyhow::{Context, Result};
use c2pa_rust_digicert_example::{
    sign_image_file, SignImageRequest, SigningImplementation,
};

fn required_env(key: &str) -> Result<String> {
    env::var(key).with_context(|| format!("Missing required environment variable: {key}"))
}

fn env_or_default(key: &str, default: &str) -> String {
    env::var(key).unwrap_or_else(|_| default.to_string())
}

fn env_bool_or_default(key: &str, default: bool) -> bool {
    env::var(key)
        .ok()
        .and_then(|value| value.parse::<bool>().ok())
        .unwrap_or(default)
}

fn signing_implementation_from_env() -> SigningImplementation {
    match env::var("C2PA_SIGNING_IMPLEMENTATION") {
        Ok(value) if value.eq_ignore_ascii_case("cawg") => SigningImplementation::CawgIdentity,
        Ok(value) if value.eq_ignore_ascii_case("cawg_identity") => SigningImplementation::CawgIdentity,
        Ok(value) if value.eq_ignore_ascii_case("standard") => SigningImplementation::Standard,
        Ok(value) if value.eq_ignore_ascii_case("standard_from_path") => SigningImplementation::StandardFromPath,
        Ok(value) if value.eq_ignore_ascii_case("cawg_from_path") => SigningImplementation::CawgIdentityFromPath,
        Ok(value) if value.eq_ignore_ascii_case("cawg_identity_from_path") => SigningImplementation::CawgIdentityFromPath,
        _ => SigningImplementation::Standard,
    }
}

fn main() -> Result<()> {
    let signing_implementation = signing_implementation_from_env();

    let mut request = SignImageRequest::with_defaults(
        required_env("C2PA_IMAGE_INPUT_PATH")?,
        required_env("C2PA_IMAGE_OUTPUT_FOLDER")?,
        required_env("C2PA_BINARY_PATH")?,
        required_env("C2PA_ACCOUNT_ID")?,
        required_env("C2PA_API_KEY")?,
        required_env("C2PA_SIGNING_SERVICE_URL")?,
    );

    request.user_id = env::var("C2PA_USER_ID").unwrap_or_default();

    request.tsa_url = env_or_default("C2PA_TSA_URL", "http://timestamp.digicert.com");
    request.roles_csv = env_or_default("C2PA_ROLES_CSV", "creator");
    request.skip_ssl_validation = env_bool_or_default("C2PA_SKIP_SSL_VALIDATION", true);
    request.skip_c2pa_public_trust_list_check =
        env_bool_or_default("SKIP_C2PA_PUBLIC_TRUST_LIST_CHECK", false);
    request.signing_implementation = signing_implementation;
    request.cawg_training_mining_json = env::var("C2PA_CAWG_TRAINING_MINING_JSON").ok();
    request.smime_credential_id = if matches!(signing_implementation, SigningImplementation::CawgIdentity | SigningImplementation::CawgIdentityFromPath) {
        Some(required_env("C2PA_SMIME_CREDENTIAL_ID")?)
    } else {
        env::var("C2PA_SMIME_CREDENTIAL_ID").ok()
    };
    request.user_pin = if matches!(signing_implementation, SigningImplementation::CawgIdentity | SigningImplementation::CawgIdentityFromPath) {
        Some(required_env("C2PA_USER_PIN")?)
    } else {
        env::var("C2PA_USER_PIN").ok()
    };

    let result = sign_image_file(request)?;

    println!("Output       : {}", result.output_path.display());
    println!("Output size  : {} bytes", result.output_size);
    if let Some(id) = result.manifest_id {
        println!("Manifest ID  : {id}");
    }
    println!("Done.");

    Ok(())
}
