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

use ocpi_tariffs::{cdr, json, price, timezone, warning, Version};

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

    // First the raw JSON is parsed into a `json::Document` and the OCPI version of the CDR is
    // guessed. The `guess::CdrVersion` returned from calling `cdr::infer_version` is either certain
    // or uncertain about the version of the contained `cdr::Versioned` object.
    let cdr = json::parse_object(CDR_JSON).expect("Unable to parse CDR JSON");
    let cdr = cdr::infer_version(cdr);

    // The guessed Version can be either certain or uncertain.
    // If the version is uncertain then fallback to presuming the CDR is v211.
    let cdr = cdr.certain_or(Version::V211);
    let cdr = cdr::build_versioned(cdr).ignore_warnings();

    // The timezone can be inferred or found in the CDR, but a versioned CDR is required.
    let timezone = match timezone::find_or_infer(&cdr) {
        Ok(tz) => tz,
        Err(err_set) => {
            let (error, warnings) = err_set.into_parts();
            eprintln!("Unable to infer timezone");
            print_timezone_error(&error);
            print_timezone_warnings(&warnings);
            return;
        }
    };
    let (timezone_source, warnings) = timezone.into_parts();

    if !warnings.is_empty() {
        print_timezone_warnings(&warnings);
    }

    // We don't care whether the timezone was found or inferred.
    let timezone = timezone_source.into_timezone();

    let report = match cdr::price(&cdr, price::TariffSource::UseCdr, timezone) {
        Ok(r) => r,
        Err(set) => {
            let (error, warnings) = set.into_parts();
            print_pricing_error(&error);
            print_pricing_warnings(&warnings);
            return;
        }
    };

    let (report, warnings) = report.into_parts();

    print_pricing_warnings(&warnings);

    // The various fields of the `price::Report` can be examined or converted to JSON.
    let price::Report {
        periods: _,
        tariff_used: _,
        tariff_reports: _,
        timezone: _,
        billed_energy: _,
        billed_idle_time: _,
        total_charging_time: _,
        billed_charging_time: _,
        total_cost: _,
        total_fixed_cost: _,
        total_time: _,
        total_charging_time_cost: _,
        total_energy: _,
        total_energy_cost: _,
        total_idle_time: _,
        total_idle_cost: _,
    } = report;
}

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

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

    eprintln!(
        "WARN: {} warnings from the timezone search",
        warnings.len_warnings()
    );

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

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

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

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