from __future__ import annotations

from copy import deepcopy
from typing import Optional, List, Union
from uuid import uuid4

from pydantic import BaseModel, Field
from sysnet_pyutils.models.general import MetadataTypeBase, LinkedType, MetadataType
from sysnet_pyutils.utils import local_now

from cites_model.cites_common import GeneralType, TransactionType, ConditionsType, IssuingType, OtherType, \
    PermitSpecialConditionsType, DocumentPrincipalCustomsPermitType, GoodsPrincipalType, WorkflowListType, \
    BaseEntryListType, EntryType, GoodsPrincipalTypeWrite, ConditionsLegacyType, PermitIdentifierType, PermitTypeEnum, \
    DocumentPrincipalCustomsGoodsType, RelatedType


class CitesDocumentEntryListType(BaseEntryListType):
    query: Optional[str] = Field(default=None, description='Dotaz na data', examples=['ftserach("luňák")'])
    entries: Optional[List[Optional[EntryType]]] = Field(default=None, description='Položky seznamu')


class CitesDocumentPrincipalTypeWrite(BaseModel):
    doc_code: Optional[str] = Field(default=None, description='Kód dokumentu - vazba na šablony', examples=['DD01'])
    metadata: Optional[MetadataTypeBase] = Field(default=None, description='Zapisovaná metadata')
    document: Optional[GeneralType] = Field(default=None, description='Základní data dokumentu')
    transaction: Optional[List[Optional[TransactionType]]] = Field(default=None, description='Seznam transakčních údajů')
    conditions: Optional[ConditionsType] = Field(default=None, description='Podmínky vydání dokumentu')
    conditions_legacy: Optional[ConditionsLegacyType] = Field(default=None, description='Podmínky pro historické výjimky DD64')
    issuing: Optional[IssuingType] = Field(default=None, description='Vydavatel')
    other: Optional[OtherType] = Field(default=None, description='Další údaje')
    permit_conditions: Optional[PermitSpecialConditionsType] = Field(default=None, description='Podmínky permitu')
    customs: Optional[DocumentPrincipalCustomsPermitType] = Field(default=None, description='Celní údaje permitu')
    goods: Optional[List[Optional[GoodsPrincipalTypeWrite]]] = Field(default=None, description='Seznam zboží')
    note: Optional[str] = Field(default=None, description='Poznámky')
    comment: Optional[str] = Field(default=None, description='Obecná poznámka')
    workflow: Optional[WorkflowListType] = Field(default=None, description='Historie životního cyklu')
    linked_list: Optional[List[Optional[LinkedType]]] = Field(default=None, description='Seznam provázaných dat')

    def get_goods_by_order(self, order: Union[int, str] = 1) -> Optional[GoodsPrincipalType]:
        if order is None:
            return None
        if self.goods:
            if isinstance(order, str):
                try:
                    order = int(order)
                except ValueError:
                    pass
            for good in self.goods:
                if isinstance(order, int):
                    if good.order.num_value == order:
                        return good
                elif isinstance(order, str):
                    if good.order.text_value == order:
                        return good
        return None

    @property
    def application(self) -> CitesDocumentPrincipalTypeWrite:
        """Vrátí žádost"""
        permit_copy  = deepcopy(self)
        permit_id_no = self.metadata.id_no
        # permit_identifier = self.identifier
        out = CitesDocumentPrincipalTypeWrite(**permit_copy.model_dump())
        out.doc_code = 'DD08'
        out.other.related_permit =  PermitIdentifierType(
            number=self.metadata.id_no,
            permit_type=self.document.permit_type,
            country=self.document.permit_country[:2] if self.document.permit_country else 'CZ',
            token=self.document.permit_token,
        )
        out.metadata.id_no = None
        out.metadata.id_no_list = []
        out.metadata.uuid_external = str(uuid4())
        out.metadata.title = f"Žádost o nový permit na základě permitu: {permit_id_no}"

        # pomocné proměnné
        # date_valid = self.permit.dateValid
        permit_last = self.metadata.id_no
        country_export = self.document.exporter.country
        # country_last = self.document.exporter.country
        country_import = self.document.importer.country
        # date_last = self.issuing.date_issued
        date_now = local_now()
        permit_type = PermitTypeEnum.IMPORT

        # upravit header
        if self.document.permit_type in [PermitTypeEnum.EXPORT, PermitTypeEnum.RE_EXPORT]:
            out.document.permit_type = PermitTypeEnum.IMPORT
        elif self.document.permit_type == PermitTypeEnum.IMPORT:
            out.document.permit_type = PermitTypeEnum.RE_EXPORT
        else:
            out.document.permit_type = PermitTypeEnum.OTHER
        out.document.country_export = str(country_export)
        out.document.country_import = str(country_import)
        out.customs =  DocumentPrincipalCustomsPermitType()
        out.issuing = IssuingType(date_issued=date_now)
        out.metadata.id_no_local = permit_last
        out.document.permit_type = permit_type
        out.document.stamp_no = None
        out.document.used = 'APPLICATION'
        out.linked_list = [LinkedType(
            title=f"Zdrojový permit: {self.metadata.id_no}",
            code='DD09',
            id=self.metadata.id_no,
            uuid=self.metadata.uuid_external,
        )]
        # zboží
        for g in out.goods:
            g.transaction_re_export =  TransactionType(
                name='LAST_RE_EXPORT',
                country=deepcopy(g.transaction_external.country),
                date_issued=deepcopy(g.transaction_external.date_issued),
                permit_type= PermitTypeEnum.EXPORT,
                permit=deepcopy(g.transaction_external.permit),
            )
            g.transaction_external = None
            g.goods_customs = DocumentPrincipalCustomsGoodsType(
                certificate=self.customs.certificate,
                comment=None,
                date_customs=self.customs.date_customs,
                dead=float(0),
                id_customs=None,
                quantity=float(0),
                type_customs=self.customs.type_customs,
            )
            g.related =[RelatedType(
                title=f"Zdrojový permit: {self.metadata.id_no}",
                uuid=self.metadata.uuid_external,
                id_no=self.metadata.id_no,
                form='permit',
            )]
        out.other.e_permit_status = None
        return out


class CitesDocumentPrincipalType(CitesDocumentPrincipalTypeWrite):
    metadata: Optional[MetadataType] = Field(default=None, description='Úplná metadata')
    goods: Optional[List[Optional[GoodsPrincipalType]]] = Field(default=None, description='Seznam zboží')
    history: Optional[List[Optional[str]]] = Field(default=None, description='Historie dokumentu ($History)')

    @property
    def purpose_traces(self):
        # Účel pro Traces. Použije se účel prvního zboží
        if self.goods:
            out = self.goods[0].purpose
            return out
        return None

    @property
    def token(self):
        # Token pro výměnný model
        out = self.metadata.pid
        if self.document.permit_token not in ['', None] and isinstance(self.document.permit_token, str):
            out = self.document.permit_token
        return out
