"""
Tareas Celery para importación CSV de Tipos de Cambio.
Flujo: scan_file (validación) → insert_valid_rows (commit).
Usa layouts_csv.common (storage, normalize, meta, responses, csv_reader).
"""
import json
import logging
import os
from typing import Dict, Any, Optional, List

from core.celery_app import celery_app
from core.database import CoreSessionLocal

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
from .validators import validate_row_exchange_rate
from .common.mappers import row_to_exchange_rate_data

logger = logging.getLogger(__name__)

JOB_TYPE = "er"
TEMPLATE_ID = "exchange_rates"

# Para routes.py
ER_IMPORT_FILE_PREFIX = "er_import_file:"
ER_IMPORT_META_PREFIX = "er_import_meta:"
ER_IMPORT_ERROR_LINES_PREFIX = "er_import_error_lines:"
ER_IMPORT_REDIS_TTL = common_storage.IMPORT_REDIS_TTL


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


def _do_scan(job_id: str, progress_callback: Optional[Any] = None) -> Dict[str, Any]:
    file_path = common_storage.ensure_file_from_redis(JOB_TYPE, job_id, "ER import")
    if not file_path:
        return {"status": "failed", "error": "Archivo no encontrado (expirado o no subido). Sube de nuevo."}
    common_storage.ensure_meta_from_redis(JOB_TYPE, job_id, file_path, "ER import")

    error_path = common_storage.error_path_for_job(JOB_TYPE, job_id)

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

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

    meta = common_meta.load_meta(file_path)
    # Formato activo del selector del frontend; si no viene, mismo default que el front (dd/mm/yyyy)
    date_format_preference = meta.get("date_format") or meta.get("dateFormat") or "dd/mm/yyyy"

    error_count = 0
    processed_rows = 0
    errors_detail: List[Dict[str, Any]] = []
    error_lines_list: List[int] = []

    try:
        with open(error_path, "w", encoding="utf-8") as f_err:
            for i, row in common_csv_reader.iter_csv_rows(file_path):
                if progress_callback:
                    progress_callback(i, total_rows, error_count)

                row_norm = _norm_row(row)
                row_errors = validate_row_exchange_rate(
                    row_norm,
                    i,
                    raw_row=row,
                    date_format_preference=date_format_preference,
                )
                if row_errors:
                    has_blocking_error = any(not e.get("warning", False) for e in row_errors)
                    if has_blocking_error:
                        error_count += 1
                        error_lines_list.append(i)
                        for e in row_errors:
                            if not e.get("warning", False):
                                f_err.write(json.dumps(e) + "\n")
                    if len(errors_detail) < 500:
                        for e in row_errors:
                            if len(errors_detail) >= 500:
                                break
                            errors_detail.append({
                                "line": e["line"],
                                "col": e.get("col", ""),
                                "msg": e.get("msg", ""),
                                "solution": e.get("solution", ""),
                                "warning": bool(e.get("warning", False)),
                            })
                processed_rows += 1

        if error_lines_list:
            common_storage.store_error_lines(JOB_TYPE, job_id, error_lines_list)
    except Exception as e:
        logger.error("ER import scan failed: %s", e)
        return {"status": "failed", "error": str(e)}

    return common_responses.scan_result(job_id, processed_rows, error_count, errors_detail)


@celery_app.task(bind=True)
def scan_file(self, job_id: str, config: str = None):
    logger.info("ER import: starting scan for job %s", job_id)

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

    return _do_scan(job_id, progress_callback=on_progress)


def _do_commit(job_id: str) -> Dict[str, Any]:
    file_path = common_storage.ensure_file_from_redis(JOB_TYPE, job_id, "ER import")
    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:
        common_storage.ensure_meta_from_redis(JOB_TYPE, job_id, file_path, "ER import")

    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)

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

    meta = common_meta.load_meta(file_path)
    reemplazar_sin_preguntar = meta.get("reemplazar_sin_preguntar", True)
    date_format_preference = meta.get("date_format") or meta.get("dateFormat")

    from api.v1.modules.a76.general_catalogs.exchange_rate.models import ExchangeRate

    inserted_count = 0
    updated_count = 0
    skipped_duplicate = 0
    skipped_invalid = 0
    skipped_details: List[Dict[str, Any]] = []
    meta_path = common_meta.get_meta_path(file_path)

    try:
        with CoreSessionLocal() as session:
            existing_by_date: Dict[tuple, ExchangeRate] = {}
            for er in (
                session.query(ExchangeRate)
                .filter(
                    ExchangeRate.tenant_id == tenant_id,
                    ExchangeRate.company_id == company_id,
                )
                .all()
            ):
                d = er.date.date() if hasattr(er.date, "date") else er.date
                existing_by_date[(tenant_id, company_id, d)] = er

            for i, row in common_csv_reader.iter_csv_rows(file_path):
                if i in error_lines:
                    continue

                row_norm = _norm_row(row)
                row_errors = validate_row_exchange_rate(
                    row_norm,
                    i,
                    raw_row=row,
                    date_format_preference=date_format_preference,
                )
                if row_errors and any(not e.get("warning", False) for e in row_errors):
                    skipped_invalid += 1
                    blocking_errors = [e for e in row_errors if not e.get("warning", False)]
                    for blocking in blocking_errors:
                        skipped_details.append({
                            "line": i,
                            "reason": f"{blocking.get('col', '')}: {blocking.get('msg', '')}",
                            "solution": blocking.get("solution", ""),
                        })
                    continue

                data = row_to_exchange_rate_data(row_norm, tenant_id, company_id, date_format_preference)
                if not data or not data.get("date"):
                    skipped_invalid += 1
                    skipped_details.append(
                        {
                            "line": i,
                            "reason": "FECHA o VALOR no válidos",
                            "solution": "Capturar en la columna FECHA una fecha válida y en la columna VALOR un número válido.",
                        }
                    )
                    continue

                key_date = data["date"].date() if hasattr(data["date"], "date") else data["date"]
                existing = existing_by_date.get((tenant_id, company_id, key_date))
                if existing:
                    if not reemplazar_sin_preguntar:
                        skipped_duplicate += 1
                        continue
                    existing.value = data["value"]
                    existing.local_currency = data.get("local_currency")
                    existing.foreign_currency = data.get("foreign_currency")
                    session.add(existing)
                    updated_count += 1
                else:
                    new_er = ExchangeRate(**data)
                    session.add(new_er)
                    existing_by_date[(tenant_id, company_id, key_date)] = new_er
                    inserted_count += 1

            try:
                session.commit()
            except Exception as db_err:
                session.rollback()
                logger.error("ER import DB error: %s", db_err)
                return {"status": "failed", "error": str(db_err)}

    except Exception as e:
        logger.exception("ER import task failed")
        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,
    )

    if inserted_count == 0 and updated_count == 0 and (skipped_invalid > 0 or skipped_duplicate > 0):
        return {
            "status": "warning",
            "inserted": 0,
            "updated": 0,
            "skipped_invalid": skipped_invalid,
            "skipped_duplicate": skipped_duplicate,
            "skipped_missing_fk": 0,
            "skipped_details": skipped_details,
            "message": f"No se insertaron registros. {skipped_invalid} rechazados, {skipped_duplicate} omitidos por fecha existente.",
        }
    if inserted_count == 0 and updated_count == 0:
        return {
            "status": "failed",
            "error": "No hay registros válidos en el archivo CSV",
            "inserted": 0,
            "updated": 0,
            "skipped_invalid": skipped_invalid,
            "skipped_duplicate": skipped_duplicate,
            "skipped_missing_fk": 0,
            "skipped_details": skipped_details,
        }
    return {
        "status": "finished",
        "inserted": inserted_count,
        "updated": updated_count,
        "skipped_invalid": skipped_invalid,
        "skipped_duplicate": skipped_duplicate,
        "skipped_missing_fk": 0,
        "skipped_details": skipped_details,
    }


@celery_app.task(bind=True)
def insert_valid_rows(self, job_id: str):
    logger.info("ER import: starting commit for job %s", job_id)
    return _do_commit(job_id)
