"""Hot Watcher Service for Automated UNC & Bank Statement Ingestion.

Monitors and scans the Finance/UNC-2026 directories (ACB-2026, Techcombank-2026, VPBank 2026)
to continuously ingest newly added bank statement files into the ERP system.
"""

from __future__ import annotations

import logging
import os
from typing import Any

from app.core.postgres.base_pkg.base_client import BasePostgresClient
from app.modules.banking.application.unc_classifier_and_router import (
    HOT_WATCHER_ROOT,
    UncClassifierAndRouter,
)

logger = logging.getLogger("dscons.banking.unc_hot_watcher")


class UncHotWatcherService:
    """Service to scan and ingest all bank statement files in the Hot Watcher folders."""

    def __init__(self, postgres_client: Any | None = None) -> None:
        self._client = postgres_client or BasePostgresClient()
        self._router = UncClassifierAndRouter(self._client)

    def scan_all_folders(self) -> dict[str, Any]:
        """Scans all subfolders in Finance/UNC-2026 and ingests new transactions."""
        if not os.path.exists(HOT_WATCHER_ROOT):
            os.makedirs(HOT_WATCHER_ROOT, exist_ok=True)
            return {
                "status": "empty",
                "message": f"Hot folder root created at {HOT_WATCHER_ROOT}",
                "files_scanned": 0,
                "transactions_ingested": 0,
            }

        total_files = 0
        total_parsed = 0
        total_saved = 0
        details = []

        # Scan all subdirectories
        for root, _, files in os.walk(HOT_WATCHER_ROOT):
            for file in files:
                ext = os.path.splitext(file)[1].lower()
                if ext not in [".xlsx", ".xls", ".pdf"]:
                    continue

                full_path = os.path.join(root, file)
                # Determine bank code from directory or filename
                folder_name = os.path.basename(root).upper()
                bank_code = None
                if "ACB" in folder_name:
                    bank_code = "ACB"
                elif "TECHCOM" in folder_name:
                    bank_code = "TECHCOMBANK"
                elif "VPBANK" in folder_name or "VPB" in folder_name:
                    bank_code = "VPBANK"

                try:
                    res = self._router.ingest_statement_file(
                        file_path=full_path, bank_code=bank_code
                    )
                    total_files += 1
                    total_parsed += res.get("total_parsed", 0)
                    total_saved += res.get("newly_saved", 0)
                    details.append(res)
                except Exception as e:
                    logger.error("Failed to process hot watcher file '%s': %s", full_path, e)
                    details.append({
                        "status": "error",
                        "file_name": file,
                        "file_path": full_path,
                        "error": str(e),
                    })

        logger.info(
            "Hot Watcher Scan Completed: %d files processed, %d txs parsed, %d new txs saved",
            total_files,
            total_parsed,
            total_saved,
        )

        return {
            "status": "success",
            "files_scanned": total_files,
            "total_parsed": total_parsed,
            "newly_saved": total_saved,
            "details": details,
        }


def main():
    print("=== RUNNING UNC HOT WATCHER SCAN ===")
    service = UncHotWatcherService()
    res = service.scan_all_folders()
    print(f"Files scanned: {res['files_scanned']}")
    print(f"Total parsed transactions: {res['total_parsed']}")
    print(f"Newly saved transactions: {res['newly_saved']}")
    print("=== SCAN FINISHED ===")


if __name__ == "__main__":
    main()
