from __future__ import annotations

import logging

from app.core.postgres.erp_client import ErpDatabaseClient
from app.core.settings import get_settings
from app.modules.agents.application.llm_client import LLMClient

from .analyzer import DocumentAnalyzerMixin
from .extractor import DocumentExtractorMixin
from .pipeline import DocumentPipelineMixin
from .validator import DocumentValidatorMixin

logger = logging.getLogger("dscons.document_processing")


class DocumentProcessingService(
    DocumentExtractorMixin,
    DocumentAnalyzerMixin,
    DocumentValidatorMixin,
    DocumentPipelineMixin,
):
    """Handles text extraction and agentic metadata analysis for construction files."""

    def __init__(
        self,
        erp_client: ErpDatabaseClient | None = None,
        llm_client: LLMClient | None = None,
    ) -> None:
        self._erp_client = erp_client or ErpDatabaseClient()
        self._llm_client = llm_client or LLMClient(get_settings())

    def resolve_upload_context(self, project_code: str | None = None) -> tuple[str, str | None]:
        """Lấy default company_id và project_id tương ứng với project_code."""
        with self._erp_client.get_connection() as conn:
            with conn.cursor() as cur:
                cur.execute("SELECT id FROM companies LIMIT 1;")
                row = cur.fetchone()
                if not row:
                    raise ValueError("Không tìm thấy công ty nào trong hệ thống để gán văn bản.")
                company_id = str(row["id"])

                project_id = None
                if project_code:
                    cur.execute(
                        "SELECT id FROM projects WHERE project_code = %s LIMIT 1;",
                        (project_code,),
                    )
                    proj_row = cur.fetchone()
                    if proj_row:
                        project_id = str(proj_row["id"])

        return company_id, project_id

