from __future__ import annotations

from typing import Any, Literal

from pydantic import BaseModel, ConfigDict, Field


class PostFinanceImportRequest(BaseModel):
    model_config = ConfigDict(extra="forbid")

    zip_content_base64: str = Field(min_length=4, max_length=66_666_668)
    overview_content_base64: str = Field(min_length=4, max_length=16_000_000)
    zip_file_name: str = Field(
        default="postfinance-documents.zip", max_length=180, pattern=r"(?i)^.*\.zip$"
    )
    overview_file_name: str = Field(
        default="postfinance-account-overview.pdf", max_length=180, pattern=r"(?i)^.*\.pdf$"
    )
    zip_mime_type: Literal["application/zip", "application/x-zip-compressed"]
    overview_mime_type: Literal["application/pdf"]
    zip_size_bytes: int = Field(ge=1, le=50_000_000)
    overview_size_bytes: int = Field(ge=1, le=12_000_000)



class PostFinanceConfirmRequest(PostFinanceImportRequest):
    preview_id: str
    confirmation_id: str
    confirm: bool = False


class PostFinancePreviewResponse(BaseModel):
    preview_id: str
    confirmation_id: str
    parser_id: str
    parser_version: str
    snapshot_at: str
    valuation_date: str
    document_count: int
    zip_document_count: int
    page_count: int
    document_types: dict[str, int]
    covered_periods: list[dict[str, str]]
    document_date_from: str | None = None
    document_date_to: str | None = None
    activity_period_from: str | None = None
    activity_period_to: str | None = None
    position_count: int
    cash_count: int
    components: list[dict[str, Any]]
    event_count: int
    event_counts: dict[str, int]
    quality_counts: dict[str, int]
    transfer_group_count: int
    total_chf: str
    securities_chf: str
    cash_chf: str
    stocks_chf: str
    etfs_chf: str
    component_total_chf: str
    reconciliation_difference_chf: str
    reconciliation_status: str
    open_orders: int
    mapped_position_count: int
    mappings: dict[str, int]
    duplicate: bool
    conflict: bool
    confirm_allowed: bool
    blocker_codes: list[str]
    data_gaps: list[str]
    next_action: str
    source_references: dict[str, str]
    warnings: list[str]


class PostFinanceConfirmResponse(BaseModel):
    status: str
    batch_id: str
    snapshot_id: str | None = None
    audit_id: str
    idempotent: bool


class PostFinanceSummaryResponse(BaseModel):
    latest_snapshot: dict[str, Any] | None
    positions: list[dict[str, Any]]
    cash: list[dict[str, Any]]
    event_counts: dict[str, int]
    imports: list[dict[str, Any]]
