"""Concrete GDT Portal Adapter implementing GdtGatewayPort.

Encapsulates GDT Portal authentication, captcha resolution, batch invoice fetching,
and line-item detail scraping into a single port-compliant class.
"""
from __future__ import annotations

import logging
from typing import Any

from app.core.postgres.base import BasePostgresClient
from app.modules.invoices.domain.ports.gdt_gateway_port import GdtGatewayPort
from .gdt_auth import InvoiceGdtAuthMixin
from .gdt_captcha import InvoiceGdtCaptchaMixin
from .gdt_detail_enrich import InvoiceGdtDetailEnrichMixin
from .gdt_detail_sync import InvoiceGdtDetailSyncMixin
from .gdt_fetcher import InvoiceGdtFetcherMixin

logger = logging.getLogger("dscons.invoices.gdt_adapter")


class GdtPortalAdapter(
    BasePostgresClient,
    InvoiceGdtAuthMixin,
    InvoiceGdtFetcherMixin,
    InvoiceGdtDetailEnrichMixin,
    InvoiceGdtDetailSyncMixin,
    GdtGatewayPort,
):
    """Secondary Outbound Infrastructure Adapter for General Department of Taxation Portal."""

    def authenticate_portal(
        self,
        tax_code: str,
        username: str,
        password: str,
        extra_config: dict[str, Any] | None = None,
    ) -> dict[str, Any]:
        """Authenticate with GDT portal, solving captcha automatically."""
        return self._authenticate_gdt_portal(
            tax_code=tax_code,
            username=username,
            password=password,
            extra_config=extra_config or {},
        )

    def solve_captcha(self) -> tuple[str, str]:
        """Fetch and solve GDT captcha returning (captcha_key, captcha_value)."""
        return self._solve_gdt_captcha()

    def fetch_invoices(
        self,
        token: str,
        from_date: str,
        to_date: str,
        sync_type: str = "all",
        tax_code: str | None = None,
        cookie_header: str = "",
    ) -> tuple[int, int, list[dict[str, Any]]]:
        """Fetch invoice batch from GDT portal."""
        return self._fetch_and_persist_gdt_invoices(
            token=token,
            from_date=from_date,
            to_date=to_date,
            sync_type=sync_type,
            tax_code=tax_code,
            cookie_header=cookie_header,
        )

    def enrich_invoice_detail(
        self,
        invoice_id: str,
        inv_data: dict[str, Any],
    ) -> dict[str, Any] | None:
        """Fetch and persist line items from GDT portal on-demand."""
        return self._enrich_gdt_invoice_detail_on_demand(
            invoice_id=invoice_id,
            inv_data=inv_data,
        )

    def sync_invoice_detail(
        self,
        invoice_id: str,
    ) -> dict[str, Any]:
        """Direct single invoice detail sync from GDT portal."""
        return self.sync_gdt_invoice_detail(invoice_id=invoice_id)
