from datetime import datetime
from typing import Self

from pydantic import BaseModel, model_validator
from pydantic_xml import BaseXmlModel, attr, element

from bb_integrations_lib.models.fuelquest.delivery import DeliveryConfirmation
from bb_integrations_lib.models.fuelquest.invoice import FuelFreightInvoice
from bb_integrations_lib.models.fuelquest.shared import (
    FuelQuestDate,
    FuelQuestTime,
    ReportType,
)


class TransmissionHeader(BaseXmlModel):
    """
    Transmission header for NAXMLDelivery files. Note that setting up transmission date / time is strange - they will be
    overwritten by the transmission_datetime field
    """

    transmission_id: str = element(tag="TransmissionId")
    transmission_datetime: datetime = element(exclude=True)
    transmission_date: FuelQuestDate | None = element(
        tag="TransmissionDate", default=None
    )
    transmission_time: FuelQuestTime | None = element(
        tag="TransmissionTime", default=None
    )

    @model_validator(mode="after")
    def populate_trans_dt(self) -> Self:
        self.transmission_date = self.transmission_datetime.date()
        self.transmission_time = self.transmission_datetime.time()
        return self

    transmission_status: ReportType = element(tag="TransmissionStatus")
    transmission_sender: str = element(tag="TransmissionSender")
    transmission_receiver: str = element(tag="TransmissionReceiver")


class DeliveryReport(BaseXmlModel):
    reportType: ReportType = attr(name="reportType")
    fuel_freight_invoice: FuelFreightInvoice = element(tag="FuelFreightInvoice")
    delivery_confirmation: list[DeliveryConfirmation] = element(
        tag="DeliveryConfirmation"
    )


class FuelQuestNAXMLDelivery(
    BaseXmlModel,
    tag="NAXML-Delivery",
    nsmap={
        "xsi": "http://www.w3.org/2001/XMLSchema-instance",
        "xsd": "http://www.w3.org/2001/XMLSchema",
    },
):
    transmission_header: TransmissionHeader = element(tag="TransmissionHeader")
    delivery_report: DeliveryReport = element(tag="DeliveryReport")


class FuelQuestConfig(BaseModel):
    sender_fq_id: str
    receiver_fq_id: str
    carrier_name: str
    carrier_ident: str
    carrier_home_state: str
    carrier_emails: list[str] = []
    source_system: str
    ftp_destination_dir: str
    enabled_counterparties: list[str]
    enabled_store_markets: list[str] | None = None
