from __future__ import annotations

import logging
from typing import Any

from fastapi import APIRouter, Depends, HTTPException, Query

from app.modules.auth.presentation.auth import require_role
from app.modules.invoices.application.invoice_processing_service import InvoiceProcessingService

from .models import (
    SchedulerPauseRequest,
    SyncConfigRequest,
    SyncGdtRequest,
    TestConnectionRequest,
)

logger = logging.getLogger("dscons.api.invoices")
router = APIRouter(
    prefix="/v1/erp/invoices",
    tags=["E-Invoices & Tax Management"],
    dependencies=[Depends(require_role(["superadmin", "director", "accountant"]))],
)
invoice_router = router
invoice_service = InvoiceProcessingService()


@invoice_router.post(
    "/sync/test-connection",
    summary="Kiểm tra kết nối thử nghiệm tới Cổng Thuế hoặc Email IMAP",
)
async def test_sync_connection(
    req: TestConnectionRequest,
    current_user: dict[str, Any] = Depends(
        require_role(["superadmin", "director", "accountant"])
    ),
) -> dict[str, Any]:
    """Kiểm tra trực tiếp thông tin đăng nhập với server Cổng Thuế hoặc IMAP."""
    res = invoice_service.test_connection(
        service_type=req.service_type,
        tax_code=req.tax_code,
        username=req.username,
        password=req.password,
        extra_config=req.extra_config,
    )
    return res


@invoice_router.get(
    "/sync/configs", summary="Lấy cấu hình kết nối Cổng Thuế & Hòm thư Hóa đơn"
)
async def get_sync_configurations(
    current_user: dict[str, Any] = Depends(
        require_role(["superadmin", "director", "accountant"])
    ),
) -> dict[str, Any]:
    """Danh sách cấu hình kết nối thực tế."""
    configs = invoice_service.get_sync_configs()
    return {"status": "success", "configs": configs}


@invoice_router.post(
    "/sync/configs", summary="Lưu cấu hình tài khoản kết nối Cổng Thuế hoặc Email IMAP"
)
async def save_sync_configuration(
    req: SyncConfigRequest,
    current_user: dict[str, Any] = Depends(
        require_role(["superadmin", "director", "accountant"])
    ),
) -> dict[str, Any]:
    """Lưu trữ thông tin đăng nhập thực tế của kế toán/doanh nghiệp."""
    user_name = (
        current_user.get("full_name") or current_user.get("email") or "SuperAdmin"
    )
    res = invoice_service.save_sync_config(
        service_type=req.service_type,
        tax_code=req.tax_code,
        username=req.username,
        password=req.password,
        extra_config=req.extra_config,
        is_active=req.is_active,
        user_name=user_name,
    )
    return res


@invoice_router.post(
    "/sync-gdt",
    summary="Kích hoạt tiến trình đồng bộ từng phần từ Cổng Tổng Cục Thuế & Hòm Thư",
)
async def sync_gdt_tax_invoices(
    req: SyncGdtRequest | None = None,
    tax_code: str | None = Query(None, description="Mã số thuế doanh nghiệp"),
    from_date: str | None = Query(None, description="Từ ngày (YYYY-MM-DD)"),
    to_date: str | None = Query(None, description="Đến ngày (YYYY-MM-DD)"),
    sync_type: str | None = Query(None, description="Loại HĐ: all, purchase, sold"),
    current_user: dict[str, Any] = Depends(
        require_role(["superadmin", "director", "accountant"])
    ),
) -> dict[str, Any]:
    """Tiến trình đồng bộ thực tế từng phần (hỗ trợ phân loại và khoảng thời gian tùy chọn)."""
    effective_tax_code = (req.tax_code if req and req.tax_code else None) or tax_code
    effective_from_date = (
        req.from_date if req and req.from_date else None
    ) or from_date
    effective_to_date = (req.to_date if req and req.to_date else None) or to_date
    effective_sync_type = (
        (req.sync_type if req and req.sync_type else None) or sync_type or "all"
    )

    res = invoice_service.run_gdt_tax_sync(
        tax_code=effective_tax_code,
        from_date=effective_from_date,
        to_date=effective_to_date,
        sync_type=effective_sync_type,
    )
    return res


@invoice_router.post(
    "/{invoice_id}/sync-gdt-detail",
    summary="Đồng bộ danh mục mặt hàng gốc từ Cổng Tổng Cục Thuế",
)
async def sync_invoice_gdt_detail(
    invoice_id: str,
    current_user: dict[str, Any] = Depends(
        require_role(["superadmin", "director", "accountant"])
    ),
) -> dict[str, Any]:
    """Gọi trực tiếp API Detail của Cổng HĐĐT Tổng Cục Thuế để nạp danh mục hàng hóa thực tế."""
    res = invoice_service.sync_gdt_invoice_detail(invoice_id)
    return res


@invoice_router.get(
    "/sync/scheduler-status",
    summary="Kiểm tra trạng thái Lập lịch Đồng bộ Hóa đơn Tự động",
)
async def get_invoice_scheduler_status(
    current_user: dict[str, Any] = Depends(
        require_role(["superadmin", "director", "accountant"])
    ),
) -> dict[str, Any]:
    """Trả về trạng thái hoạt động của Scheduler, 6 khung giờ cố định và lần đồng bộ kế tiếp."""
    from app.modules.invoices.application.invoice_processing.auto_sync_scheduler import (
        get_invoice_auto_sync_service,
    )

    service = get_invoice_auto_sync_service()
    status_info = service.get_status()
    return {"status": "success", "scheduler": status_info}


@invoice_router.post(
    "/sync/trigger-scheduled-sync",
    summary="Kích hoạt ngay một phiên Đồng bộ Hóa đơn Định kỳ (Manual Test / Emergency)",
)
async def trigger_scheduled_sync_now(
    sync_type: str = Query("all", description="Loại hóa đơn: all, purchase, sold"),
    current_user: dict[str, Any] = Depends(
        require_role(["superadmin", "director", "accountant"])
    ),
) -> dict[str, Any]:
    """Kích hoạt tức thì một phiên đồng bộ tự động như lịch định kỳ (kèm cơ chế gửi email cảnh báo nếu lỗi)."""
    from app.modules.invoices.application.invoice_processing.auto_sync_scheduler import (
        get_invoice_auto_sync_service,
    )

    service = get_invoice_auto_sync_service()
    res = await service.execute_scheduled_sync(
        trigger_slot="MANUAL-TRIGGER", force=True, sync_type=sync_type
    )
    return {"status": "success", "result": res}


@invoice_router.post(
    "/sync/scheduler/pause",
    summary="Tạm ngưng cron job tự đồng bộ hóa đơn định kỳ (chờ mở khóa tài khoản Cục Thuế)",
)
async def pause_invoice_scheduler(
    req: SchedulerPauseRequest | None = None,
    current_user: dict[str, Any] = Depends(
        require_role(["superadmin", "director", "accountant"])
    ),
) -> dict[str, Any]:
    """Tạm ngưng cron job tự động đồng bộ hóa đơn và cập nhật trạng thái tạm khóa trong hệ thống."""
    from app.modules.invoices.application.invoice_processing.auto_sync_scheduler import (
        get_invoice_auto_sync_service,
    )

    reason = (
        req.reason
        if req and req.reason
        else "Tài khoản Cổng Tổng Cục Thuế (hoadondientu.gdt.gov.vn) bị tạm khóa do nhập sai nhiều lần. Cron job tự đồng bộ đang tạm ngưng chờ mở tài khoản."
    )
    service = get_invoice_auto_sync_service()
    service.pause(reason)

    # Vô hiệu hóa cấu hình gdt_portal trong DB để bảo vệ tài khoản
    invoice_service.deactivate_sync_config(
        service_type="gdt_portal",
        tax_code="0202111150",
        reason=reason,
        status="ACCOUNT_LOCKED",
    )

    return {
        "status": "success",
        "message": "Đã tạm ngưng cron job tự động đồng bộ hóa đơn thành công.",
        "scheduler": service.get_status(),
    }


@invoice_router.post(
    "/sync/scheduler/resume",
    summary="Khôi phục hoạt động cron job tự đồng bộ hóa đơn sau khi tài khoản được mở lại",
)
async def resume_invoice_scheduler(
    current_user: dict[str, Any] = Depends(
        require_role(["superadmin", "director", "accountant"])
    ),
) -> dict[str, Any]:
    """Khôi phục lại lịch tự động quét và đồng bộ hóa đơn định kỳ (01:00 và 13:00 hàng ngày, biên độ ±30 phút)."""
    from app.modules.invoices.application.invoice_processing.auto_sync_scheduler import (
        get_invoice_auto_sync_service,
    )

    service = get_invoice_auto_sync_service()
    service.resume()
    invoice_service.activate_sync_config(service_type="gdt_portal", tax_code="0202111150")

    return {
        "status": "success",
        "message": "Đã khôi phục hoạt động cho cron job tự động đồng bộ hóa đơn.",
        "scheduler": service.get_status(),
    }


@invoice_router.post(
    "/{invoice_id}/sync-equipment",
    summary="Đồng bộ bóc tách hóa đơn máy móc sang danh mục thiết bị sở hữu erp_equipment",
)
async def sync_invoice_to_equipment(
    invoice_id: str,
    current_user: dict[str, Any] = Depends(
        require_role(["superadmin", "director", "accountant"])
    ),
) -> dict[str, Any]:
    """Tự động bóc tách các máy móc, xe tải, thiết bị từ hóa đơn mua vào vào bảng erp_equipment."""
    try:
        res = invoice_service.sync_invoice_to_equipment(invoice_id)
        return res
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))
