"""Clasificador documental heurístico para V1 del procesamiento masivo."""

from __future__ import annotations

import re


class HeuristicDocumentClassifier:
    """Detecta el tipo documental por nombre de archivo y contenido extraído."""

    _RULES = (
        (
            "historia_clinica",
            (
                "historia clinica",
                "epicrisis",
                "evolucion",
                "anamnesis",
                "hc",
                "historia",
            ),
        ),
        (
            "factura",
            (
                "factura",
                "cuenta de cobro",
                "valor total",
                "copago",
                "soat",
                "facturacion",
            ),
        ),
        (
            "quirurgico",
            (
                "quirurg",
                "cirugia",
                "quirófano",
                "quirófano",
                "procedimiento quirurgico",
                "qx",
            ),
        ),
        (
            "laboratorio",
            (
                "laboratorio",
                "hemograma",
                "bioquimica",
                "quimica sanguinea",
                "resultado de laboratorio",
            ),
        ),
        (
            "radiologia",
            (
                "radiologia",
                "tomografia",
                "tac",
                "resonancia",
                "ecografia",
                "rayos x",
                "rx",
            ),
        ),
        (
            "prescripcion",
            (
                "formula medica",
                "prescripcion",
                "orden medica",
                "medicamento",
                "tratamiento",
            ),
        ),
    )

    def classify(self, filename: str, text: str) -> str:
        haystack = f"{filename} {text[:4000]}".lower()
        haystack = re.sub(r"[_\-]+", " ", haystack)
        for detected_type, keywords in self._RULES:
            if any(keyword in haystack for keyword in keywords):
                return detected_type
        return "generico"
