from __future__ import annotations

"""Unified GDT sync workflow mixin."""


import logging
from typing import Any

from .gdt_detail_enricher import InvoiceGdtDetailEnricherMixin
from .gdt_fetcher import InvoiceGdtFetcherMixin

logger = logging.getLogger(__name__)


class InvoiceGdtSyncMixin(InvoiceGdtFetcherMixin, InvoiceGdtDetailEnricherMixin):
    """Unified GDT sync mixin."""

    def run_gdt_tax_sync(
        self,
        tax_code: str | None = None,
        from_date: str | None = None,
        to_date: str | None = None,
        sync_type: str = "all",
    ) -> dict[str, Any]:
        """Thực hiện đồng bộ thực tế từng phần theo khoảng thời gian từ Cổng Tổng Cục Thuế (hoadondientu.gdt.gov.vn) hoặc Email IMAP."""
        with self.get_connection() as conn:
            with conn.cursor() as cur:
                if tax_code and tax_code.strip():
                    cur.execute(
                        """
                        SELECT id, service_type, tax_code, username, password_hash, extra_config, is_active
                        FROM erp_invoice_sync_configs
                        WHERE is_active = TRUE AND (tax_code = %s OR tax_code = 'DEFAULT')
                        ORDER BY updated_at DESC;
                    """,
                        (tax_code.strip(),),
                    )
                else:
                    cur.execute("""
                        SELECT id, service_type, tax_code, username, password_hash, extra_config, is_active
                        FROM erp_invoice_sync_configs
                        WHERE is_active = TRUE
                        ORDER BY updated_at DESC;
                    """)
                configs = cur.fetchall()

        if not configs:
            target_mst = tax_code if (tax_code and tax_code.strip()) else "doanh nghiệp"
            return {
                "status": "not_configured",
                "message": f"Chưa cấu hình tài khoản kết nối Cổng HĐĐT Tổng Cục Thuế (hoadondientu.gdt.gov.vn) hoặc Hòm thư Hóa đơn cho {target_mst}.",
                "requires_action": "open_config_modal",
                "gdt_portal_url": "https://hoadondientu.gdt.gov.vn",
            }

        sync_results = []
        total_new = 0
        total_dup = 0

        for cfg in configs:
            service_type = cfg["service_type"]
            cfg_tax_code = cfg["tax_code"]
            username = cfg["username"]
            password = cfg["password_hash"]
            extra = cfg["extra_config"] if isinstance(cfg["extra_config"], dict) else {}

            if service_type == "gdt_portal":
                res = self._execute_real_gdt_connection(
                    config_id=cfg["id"],
                    tax_code=cfg_tax_code,
                    username=username,
                    password=password,
                    extra=extra,
                    from_date=from_date,
                    to_date=to_date,
                    sync_type=sync_type,
                )
                sync_results.append(res)
                total_new += res.get("new_imported", 0)
                total_dup += res.get("duplicates", 0)

            elif service_type == "email_imap":
                res = self._execute_real_email_imap_sync(
                    cfg["id"], username, password, extra
                )
                sync_results.append(res)
                total_new += res.get("new_imported", 0)
                total_dup += res.get("duplicates", 0)

        failed_connectors = [
            r for r in sync_results if r.get("status") not in ("success", "cooldown_active")
        ]
        cooldown_connectors = [
            r for r in sync_results if r.get("status") == "cooldown_active"
        ]

        if failed_connectors and total_new == 0 and total_dup == 0:
            error_messages = [
                f"[{res.get('service', 'Service').upper()}] {res.get('message', '')}"
                for res in failed_connectors
            ]
            # auth_error: Cổng Thuế từ chối đăng nhập thật (tính vào ngắt mạch, cooldown 3h).
            # ai_error  : AI không đồng thuận captcha, phiên tự hủy TRƯỚC khi gửi đăng nhập
            #             -> không được gộp thành auth_error (sửa 04/10/2026).
            failed_statuses = {r.get("status") for r in failed_connectors}
            if "auth_error" in failed_statuses:
                aggregate_status = "auth_error"
            elif "ai_error" in failed_statuses:
                aggregate_status = "ai_error"
            else:
                aggregate_status = "error"
            return {
                "status": aggregate_status,
                "message": "\n".join(error_messages)
                if error_messages
                else "Không thể đồng bộ do lỗi xác thực tài khoản hoặc kết nối mạng.",
                "connectors": sync_results,
            }

        if len(cooldown_connectors) == len(sync_results) and len(sync_results) > 0:
            cooldown_messages = [
                f"[{res.get('service', 'Service').upper()}] {res.get('message', '')}"
                for res in cooldown_connectors
            ]
            return {
                "status": "cooldown_active",
                "message": "\n".join(cooldown_messages),
                "connectors": sync_results,
            }

        date_summary = (
            f"từ {from_date} đến {to_date}" if from_date and to_date else "kỳ hiện tại"
        )
        return {
            "status": "success",
            "message": f"Tiến trình đồng bộ {date_summary} hoàn tất: {total_new} hóa đơn mới đã nạp, {total_dup} hóa đơn đã tồn tại.",
            "total_new": total_new,
            "total_duplicates": total_dup,
            "from_date": from_date,
            "to_date": to_date,
            "connectors": sync_results,
        }
