//! Parse an IANA Timezone from JSON or find a timezone in a CDR.

#[cfg(test)]
pub mod test;

#[cfg(test)]
mod test_find_or_infer;

use std::{borrow::Cow, fmt};

use chrono_tz::Tz;
use tracing::{debug, instrument};

use crate::{
    cdr, country, from_warning_all,
    json::{self, FieldsAsExt as _, FromJson as _},
    warning::{self, GatherWarnings as _, WithElement as _},
    IntoCaveat as _, Verdict, Version, Versioned as _,
};

/// The warnings possible when parsing or linting an IANA timezone.
#[derive(Debug)]
pub enum Warning {
    /// A timezone can't be inferred from the `location`'s `country`.
    CantInferTimezoneFromCountry(&'static str),

    /// Neither the timezone or country field require char escape codes.
    ContainsEscapeCodes,

    /// The CDR location is not a valid `ISO 3166-1` alpha-3 code.
    Country(country::Warning),

    /// The field at the path could not be decoded.
    Decode(json::decode::Warning),

    /// The CDR location is not a String.
    InvalidLocationType,

    /// The CDR location did not contain a valid IANA time-zone.
    ///
    /// See: <https://www.iana.org/time-zones>.
    InvalidTimezone,

    /// The CDR timezone is not a String.
    InvalidTimezoneType,

    /// The `location.country` field should be an alpha-3 country code.
    ///
    /// The alpha-2 code can be converted into an alpha-3 but the caller should be warned.
    LocationCountryShouldBeAlpha3,

    /// The CDR's `location` has no `country` element and so the timezone can't be inferred.
    NoLocationCountry,

    /// The CDR has no `location` element and so the timezone can't be found or inferred.
    NoLocation,

    /// Both the CDR and tariff JSON should be an Object.
    ShouldBeAnObject,

    /// A v221 CDR is given but it contains a `location` field instead of a `cdr_location` as defined in the spec.
    V221CdrHasLocationField,
}

from_warning_all!(
    country::Warning => Warning::Country,
    json::decode::Warning => Warning::Decode
);

impl fmt::Display for Warning {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::CantInferTimezoneFromCountry(country_code) => write!(f, "Unable to infer timezone from the `location`'s `country`: `{country_code}`"),
            Self::ContainsEscapeCodes => f.write_str("The CDR location contains needless escape codes."),
            Self::Country(kind) => fmt::Display::fmt(kind, f),
            Self::Decode(warning) => fmt::Display::fmt(warning, f),
            Self::InvalidLocationType => f.write_str("The CDR location is not a String."),
            Self::InvalidTimezone => f.write_str("The CDR location did not contain a valid IANA time-zone."),
            Self::InvalidTimezoneType => f.write_str("The CDR timezone is not a String."),
            Self::LocationCountryShouldBeAlpha3 => f.write_str("The `location.country` field should be an alpha-3 country code."),
            Self::NoLocationCountry => {
                f.write_str("The CDR's `location` has no `country` element and so the timezone can't be inferred.")
            },
            Self::NoLocation => {
                f.write_str("The CDR has no `location` element and so the timezone can't be found or inferred.")                   
            }
            Self::ShouldBeAnObject => f.write_str("The CDR should be a JSON object"),
            Self::V221CdrHasLocationField => f.write_str("the v2.2.1 CDR contains a `location` field but the v2.2.1 spec defines a `cdr_location` field."),

        }
    }
}

impl crate::Warning for Warning {
    fn id(&self) -> warning::Id {
        match self {
            Self::CantInferTimezoneFromCountry(_) => {
                warning::Id::from_static("cant_infer_timezone_from_country")
            }
            Self::ContainsEscapeCodes => warning::Id::from_static("contains_escape_codes"),
            Self::Decode(warning) => warning.id(),
            Self::Country(warning) => warning.id(),
            Self::InvalidLocationType => warning::Id::from_static("invalid_location_type"),
            Self::InvalidTimezone => warning::Id::from_static("invalid_timezone"),
            Self::InvalidTimezoneType => warning::Id::from_static("invalid_timezone_type"),
            Self::LocationCountryShouldBeAlpha3 => {
                warning::Id::from_static("location_country_should_be_alpha3")
            }
            Self::NoLocationCountry => warning::Id::from_static("no_location_country"),
            Self::NoLocation => warning::Id::from_static("no_location"),
            Self::ShouldBeAnObject => warning::Id::from_static("should_be_an_object"),
            Self::V221CdrHasLocationField => {
                warning::Id::from_static("v221_cdr_has_location_field")
            }
        }
    }
}

/// The source of the timezone.
#[derive(Copy, Clone, Debug)]
pub enum Source {
    /// The timezone was found in the `location` element.
    Found(Tz),

    /// The timezone is inferred from the `location`'s `country`.
    Inferred(Tz),
}

impl Source {
    /// Return the timezone and disregard where it came from.
    pub fn into_timezone(self) -> Tz {
        match self {
            Source::Found(tz) | Source::Inferred(tz) => tz,
        }
    }
}

/// Try to find or infer the timezone from the `CDR` JSON.
///
/// Return `Some` if the timezone can be found or inferred.
/// Return `None` if the timezone is not found and can't be inferred.
///
/// Finding a timezone is an infallible operation. If invalid data is found a `None` is returned
/// with an appropriate warning.
///
/// If the `CDR` contains a `time_zone` in the location object then that is simply returned.
/// Only pre-`v2.2.1` CDR's have a `time_zone` field in the `Location` object.
///
/// Inferring the timezone only works for `CDR`s from European countries.
///
pub fn find_or_infer(cdr: &cdr::Versioned<'_>) -> Verdict<Source, Warning> {
    const LOCATION_FIELD_V211: &str = "location";
    const LOCATION_FIELD_V221: &str = "cdr_location";
    const TIMEZONE_FIELD: &str = "time_zone";
    const COUNTRY_FIELD: &str = "country";

    let mut warnings = warning::Set::new();

    let cdr_root = cdr.as_element();
    let Some(fields) = cdr_root.as_object_fields() else {
        return warnings.bail(cdr_root, Warning::ShouldBeAnObject);
    };

    let cdr_fields = fields.as_raw_map();

    let v211_location = cdr_fields.get(LOCATION_FIELD_V211);

    // OCPI v221 changed the `location` field to `cdr_location`.
    //
    // * See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_cdrs.asciidoc#131-cdr-object>
    // * See: <https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_cdrs.md#3-object-description>
    if cdr.version() == Version::V221 && v211_location.is_some() {
        warnings.insert(cdr_root, Warning::V221CdrHasLocationField);
    }

    // Describes the location that the charge-session took place at.
    //
    // The v211 CDR has a `location` field, while the v221 CDR has a `cdr_location` field.
    //
    // * See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_cdrs.asciidoc#131-cdr-object>
    // * See: <https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_cdrs.md#3-object-description>
    let Some(location_elem) = v211_location.or_else(|| cdr_fields.get(LOCATION_FIELD_V221)) else {
        return warnings.bail(cdr_root, Warning::NoLocation);
    };

    let json::Value::Object(fields) = location_elem.as_value() else {
        return warnings.bail(cdr_root, Warning::InvalidLocationType);
    };

    let location_fields = fields.as_raw_map();

    debug!("Searching for time-zone in CDR");

    // The `location::time_zone` field is optional in v211 and not defined in the v221 spec.
    //
    // See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_cdrs.asciidoc#mod_cdrs_cdr_location_class>
    // See: <https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_locations.md#31-location-object>
    let tz = location_fields
        .get(TIMEZONE_FIELD)
        .map(|elem| try_parse_location_timezone(elem).gather_warnings_into(&mut warnings))
        .transpose();

    // We first try to find/parse the timezone in the location object.
    // If the timezone is not found there or there are any failures,
    // The failures are deescalated to warnings.
    let tz = tz
        .map_err(|err_set| {
            warnings.deescalate_error(err_set);
        })
        .ok()
        .flatten();

    if let Some(tz) = tz {
        return Ok(Source::Found(tz).into_caveat(warnings));
    }

    debug!("No time-zone found in CDR; trying to infer time-zone from country");

    // `ISO 3166-1 alpha-3` code for the country of this location.
    let Some(country_elem) = location_fields.get(COUNTRY_FIELD) else {
        // The `location::country` field is required.
        //
        // See: <https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_cdrs.asciidoc#mod_cdrs_cdr_location_class>
        // See: <https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_locations.md#31-location-object>
        return warnings.bail(location_elem, Warning::NoLocationCountry);
    };
    let tz =
        infer_timezone_from_location_country(country_elem).gather_warnings_into(&mut warnings)?;

    Ok(Source::Inferred(tz).into_caveat(warnings))
}

/// Try to parse the `location` element's timezone into a `Tz`.
fn try_parse_location_timezone(tz_elem: &json::Element<'_>) -> Verdict<Tz, Warning> {
    let tz = tz_elem.as_value();
    debug!(tz = %tz, "Raw time-zone found in CDR");

    let mut warnings = warning::Set::new();
    let Some(tz) = tz.to_raw_str() else {
        return warnings.bail(tz_elem, Warning::InvalidTimezoneType);
    };

    let tz = tz
        .decode_escapes()
        .with_element(tz_elem)
        .gather_warnings_into(&mut warnings);

    if matches!(tz, Cow::Owned(_)) {
        warnings.insert(tz_elem, Warning::ContainsEscapeCodes);
    }

    debug!(%tz, "Escaped time-zone found in CDR");

    let Ok(tz) = tz.parse::<Tz>() else {
        return warnings.bail(tz_elem, Warning::InvalidTimezone);
    };

    Ok(tz.into_caveat(warnings))
}

/// Try to infer a timezone from the `location` elements `country` field.
#[instrument(skip_all)]
fn infer_timezone_from_location_country(country_elem: &json::Element<'_>) -> Verdict<Tz, Warning> {
    let mut warnings = warning::Set::new();
    let code_set = country::CodeSet::from_json(country_elem)?.gather_warnings_into(&mut warnings);

    // The `location.country` field should be an alpha-3 country code.
    //
    // The alpha-2 code can be converted into an alpha-3 but the caller should be warned.
    let country_code = match code_set {
        country::CodeSet::Alpha2(code) => {
            warnings.insert(country_elem, Warning::LocationCountryShouldBeAlpha3);
            code
        }
        country::CodeSet::Alpha3(code) => code,
    };
    let Some(tz) = try_detect_timezone(country_code) else {
        return warnings.bail(
            country_elem,
            Warning::CantInferTimezoneFromCountry(country_code.into_alpha_2_str()),
        );
    };

    Ok(tz.into_caveat(warnings))
}

/// Mapping of European countries to time-zones with geographical naming
///
/// This is only possible for countries with a single time-zone and only for countries as they
/// currently exist (2024). It's a best effort approach to determine a time-zone from just an
/// ALPHA-3 `ISO 3166-1` country code.
///
/// In small edge cases (e.g. Gibraltar) this detection might generate the wrong time-zone.
#[instrument]
#[expect(
    clippy::wildcard_enum_match_arm,
    reason = "There are many `Code` variants that do not map to a timezone."
)]
fn try_detect_timezone(country_code: country::Code) -> Option<Tz> {
    let tz = match country_code {
        country::Code::Ad => Tz::Europe__Andorra,
        country::Code::Al => Tz::Europe__Tirane,
        country::Code::At => Tz::Europe__Vienna,
        country::Code::Ba => Tz::Europe__Sarajevo,
        country::Code::Be => Tz::Europe__Brussels,
        country::Code::Bg => Tz::Europe__Sofia,
        country::Code::By => Tz::Europe__Minsk,
        country::Code::Ch => Tz::Europe__Zurich,
        country::Code::Cy => Tz::Europe__Nicosia,
        country::Code::Cz => Tz::Europe__Prague,
        country::Code::De => Tz::Europe__Berlin,
        country::Code::Dk => Tz::Europe__Copenhagen,
        country::Code::Ee => Tz::Europe__Tallinn,
        country::Code::Es => Tz::Europe__Madrid,
        country::Code::Fi => Tz::Europe__Helsinki,
        country::Code::Fr => Tz::Europe__Paris,
        country::Code::Gb => Tz::Europe__London,
        country::Code::Gr => Tz::Europe__Athens,
        country::Code::Hr => Tz::Europe__Zagreb,
        country::Code::Hu => Tz::Europe__Budapest,
        country::Code::Ie => Tz::Europe__Dublin,
        country::Code::Is => Tz::Iceland,
        country::Code::It => Tz::Europe__Rome,
        country::Code::Li => Tz::Europe__Vaduz,
        country::Code::Lt => Tz::Europe__Vilnius,
        country::Code::Lu => Tz::Europe__Luxembourg,
        country::Code::Lv => Tz::Europe__Riga,
        country::Code::Mc => Tz::Europe__Monaco,
        country::Code::Md => Tz::Europe__Chisinau,
        country::Code::Me => Tz::Europe__Podgorica,
        country::Code::Mk => Tz::Europe__Skopje,
        country::Code::Mt => Tz::Europe__Malta,
        country::Code::Nl => Tz::Europe__Amsterdam,
        country::Code::No => Tz::Europe__Oslo,
        country::Code::Pl => Tz::Europe__Warsaw,
        country::Code::Pt => Tz::Europe__Lisbon,
        country::Code::Ro => Tz::Europe__Bucharest,
        country::Code::Rs => Tz::Europe__Belgrade,
        country::Code::Ru => Tz::Europe__Moscow,
        country::Code::Se => Tz::Europe__Stockholm,
        country::Code::Si => Tz::Europe__Ljubljana,
        country::Code::Sk => Tz::Europe__Bratislava,
        country::Code::Sm => Tz::Europe__San_Marino,
        country::Code::Tr => Tz::Turkey,
        country::Code::Ua => Tz::Europe__Kiev,
        _ => return None,
    };

    debug!(%tz, "time-zone detected");

    Some(tz)
}
