#![expect(clippy::unwrap_used, reason = "examples can panic")]
#![expect(clippy::print_stdout, reason = "examples can log to stdout")]
#![expect(clippy::print_stderr, reason = "examples can log to stderr")]

use std::str::FromStr as _;

use chrono::{DateTime, Utc};
use ocpi_tariffs::{cdr, generate, json, tariff, warning, Version};
use rust_decimal::Decimal;

fn main() {
    const TARIFF_JSON: &str = include_str!("data/tariff_time_and_parking_time_separate.json");

    // Parse the raw JSON into a `json::Document` and guess the OCPI version of the tariff, falling
    // back to `v2.2.1` when the version is uncertain.
    let doc = json::parse_object(TARIFF_JSON).unwrap();
    let tariff = tariff::infer_version(doc).certain_or(Version::V221);
    let tariff = tariff::build_versioned(tariff).ignore_warnings();

    let config = generate::Config {
        timezone: chrono_tz::Europe::Amsterdam,
        start_date_time: DateTime::<Utc>::from_str("2025-06-12 18:22:33+00:00").unwrap(),
        end_date_time: DateTime::<Utc>::from_str("2025-06-12 22:33:44+00:00").unwrap(),
        max_current_supply_amp: Decimal::from(4),
        requested_kwh: Decimal::from(24),
        max_power_supply_kw: Decimal::from(80),
    };
    let report = match cdr::generate_from_tariff(&tariff, &config) {
        Ok(r) => r,
        Err(set) => {
            let (error, warnings) = set.into_parts();
            print_error(&error);
            print_warnings(&warnings);
            return;
        }
    };
    let (report, warnings) = report.into_parts();

    print_warnings(&warnings);

    let generate::Report {
        tariff_id,
        tariff_currency_code,
        partial_cdr,
    } = report;

    println!("CDR generated for tariff with id: `{tariff_id}` and currency code: `{tariff_currency_code}`");
    println!("{partial_cdr:#?}");
}

/// Print `generate::Warning` that halted the example to `stderr`.
fn print_error(error: &warning::Error<generate::Warning>) {
    eprintln!(
        "ERR: Unable to generate CDR due to error at path `{}`: {}",
        error.element().path,
        error.warning()
    );
}

/// Print `generate::Warning`s to `stderr`.
fn print_warnings(warnings: &warning::Set<generate::Warning>) {
    if warnings.is_empty() {
        return;
    }

    eprintln!(
        "WARN: {} warnings from the linting:\n {}",
        warnings.len_warnings(),
        warning::SetWriter::new(warnings)
    );
}
