"""
Tareas Celery para importación CSV de Cambio de régimen y Regularización (encabezado y partidas).
Flujo: scan_file (sin validaciones) → insert_valid_rows (sin inserción en BD).
Usa layouts_csv.common (storage, normalize, meta, responses, csv_reader).
Validaciones independientes por document_type (cam_reg vs regulariz) se añadirán después.
"""
import logging
import os
from typing import Dict, Any, Optional

from core.celery_app import celery_app

from ..common import storage as common_storage
from ..common import normalize as common_normalize
from ..common import meta as common_meta
from ..common import responses as common_responses
from ..common import csv_reader as common_csv_reader
from .template_config import row_from_template

logger = logging.getLogger(__name__)

JOB_TYPE = "crreg"
CRREG_IMPORT_REDIS_TTL = common_storage.IMPORT_REDIS_TTL


def _ensure_file(job_id: str) -> Optional[str]:
    return common_storage.ensure_file_from_redis(JOB_TYPE, job_id, "Cambio régimen/Regularización import")


def _ensure_meta(job_id: str, file_path: str) -> bool:
    return common_storage.ensure_meta_from_redis(JOB_TYPE, job_id, file_path, "Cambio régimen/Regularización import")


def _norm_row(row: Dict[str, Any], template_id: str) -> Dict[str, Any]:
    return row_from_template(row, template_id, common_normalize.normalize_header)


@celery_app.task(bind=True, name="api.v1.modules.a76.layouts_csv.cambio_regimen_regularizacion.tasks.scan_file")
def scan_file(self, job_id: str, model_target: str, config: str = None):
    """
    Scan CSV sin validaciones: leer, normalizar con plantilla, devolver total_rows y 0 errores.
    """
    logger.info("Cambio régimen/Regularización import: starting scan for job %s target %s", job_id, model_target)

    file_path = _ensure_file(job_id)
    if not file_path:
        return {"status": "failed", "error": "Archivo no encontrado (expirado o no subido). Sube de nuevo."}
    if os.path.getsize(file_path) == 0:
        return {"status": "failed", "error": "El archivo está vacío."}
    _ensure_meta(job_id, file_path)

    try:
        common_meta.require_tenant_context(file_path)
    except ValueError as e:
        return {"status": "failed", "error": str(e)}

    meta = common_meta.load_meta(file_path) or {}
    document_type = meta.get("document_type") or "cam_reg"
    template_id = meta.get("template_id") or (
        "cam_reg_header" if model_target == "invoice_header" else "cam_reg_details"
    )
    if document_type == "regulariz" and not meta.get("template_id"):
        template_id = "regulariz_header" if model_target == "invoice_header" else "regulariz_details"

    total_rows = 0
    processed_rows = 0

    try:
        total_rows = common_csv_reader.count_csv_rows(file_path, has_header=True)
    except Exception as e:
        return {"status": "failed", "error": str(e)}

    def on_progress(current: int, total: int) -> None:
        self.update_state(state="PROGRESS", meta={"current": current, "total": total})

    try:
        for i, row in common_csv_reader.iter_csv_rows(file_path, fieldnames=None):
            on_progress(i, total_rows)
            _norm_row(row, template_id)
            processed_rows += 1
    except Exception as e:
        logger.error("Cambio régimen/Regularización import scan failed: %s", e)
        return {"status": "failed", "error": str(e)}

    return common_responses.scan_result(job_id, processed_rows, 0, [])


@celery_app.task(bind=True, name="api.v1.modules.a76.layouts_csv.cambio_regimen_regularizacion.tasks.insert_valid_rows")
def insert_valid_rows(self, job_id: str, model_target: str):
    """
    Commit sin inserción en BD: leer CSV, omitir líneas de error (vacío por ahora), cleanup, devolver finished con inserted=0.
    """
    logger.info("Cambio régimen/Regularización import: starting commit for job %s target %s", job_id, model_target)

    file_path = _ensure_file(job_id)
    if not file_path:
        alt_path = common_storage.file_path_for_job(JOB_TYPE, job_id)
        if not os.path.exists(alt_path):
            return {"status": "failed", "error": "Archivo no encontrado (expirado). Sube y confirma de nuevo."}
        file_path = alt_path
    else:
        _ensure_meta(job_id, file_path)

    try:
        common_meta.require_tenant_context(file_path)
    except ValueError as e:
        return {"status": "failed", "error": str(e)}

    meta = common_meta.load_meta(file_path) or {}
    meta_path = common_meta.get_meta_path(file_path)
    error_path = common_storage.error_path_for_job(JOB_TYPE, job_id)
    error_lines = common_storage.get_error_lines(JOB_TYPE, job_id, error_path)

    document_type = meta.get("document_type") or "cam_reg"
    template_id = meta.get("template_id") or (
        "cam_reg_header" if model_target == "invoice_header" else "cam_reg_details"
    )
    if document_type == "regulariz" and not meta.get("template_id"):
        template_id = "regulariz_header" if model_target == "invoice_header" else "regulariz_details"

    try:
        for i, row in common_csv_reader.iter_csv_rows(file_path, fieldnames=None):
            if i in error_lines:
                continue
            _norm_row(row, template_id)
    except Exception as e:
        logger.error("Cambio régimen/Regularización import commit read failed: %s", e)
        return {"status": "failed", "error": str(e)}

    common_storage.cleanup_import_job(
        JOB_TYPE, job_id,
        file_path=file_path,
        error_path=error_path,
        meta_path=meta_path,
    )

    return {
        "status": "finished",
        "inserted": 0,
        "skipped_invalid": 0,
        "skipped_missing_fk": 0,
        "skipped_duplicate": 0,
        "skipped_details": [],
        "message": "Proceso base listo; validaciones e inserción pendientes.",
    }
