"""
Tareas Celery para importación CSV de Fracción Americana (US Tariff Fractions).
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_us_tariff_fraction, validate_row_desfase_fa
from .common.mappers import row_to_us_tariff_fraction_data
from .common.fk_loader import load_fa_fk_sets

logger = logging.getLogger(__name__)

JOB_TYPE = "fa"
TEMPLATE_ID = "us_tariff_fractions"

# Para routes.py
FA_IMPORT_FILE_PREFIX = "fa_import_file:"
FA_IMPORT_META_PREFIX = "fa_import_meta:"
FA_IMPORT_ERROR_LINES_PREFIX = "fa_import_error_lines:"
FA_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, "FA 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, "FA 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_data = common_meta.load_meta(file_path)
    actualizar = meta_data.get("actualizar", False)
    valid_uom_codes, existing_fraction_codes = load_fa_fk_sets(tenant_id, company_id)

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

    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)

                warn = validate_row_desfase_fa(row, i)
                if warn and len(warnings_detail) < 500:
                    warnings_detail.append({
                        "line": warn["line"],
                        "col": warn.get("col", ""),
                        "msg": warn.get("msg", ""),
                    })

                row_norm = _norm_row(row)
                row_errors = validate_row_us_tariff_fraction(
                    row_norm,
                    i,
                    actualizar=actualizar,
                    existing_fraction_codes=existing_fraction_codes,
                    valid_uom_codes=valid_uom_codes,
                    raw_row=row,
                )
                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", ""),
                            })
                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("FA import scan failed: %s", e)
        return {"status": "failed", "error": str(e)}

    result = common_responses.scan_result(job_id, processed_rows, error_count, errors_detail)
    if warnings_detail:
        result["warnings"] = warnings_detail
    return result


@celery_app.task(bind=True)
def scan_file(self, job_id: str, config: str = None):
    logger.info("FA 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, "FA 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, "FA 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_data = common_meta.load_meta(file_path)
    actualizar = meta_data.get("actualizar", False)
    valid_uom_codes, existing_fraction_codes = load_fa_fk_sets(tenant_id, company_id)

    from api.v1.modules.a76.general_catalogs.fractions.us_tariff_fractions.models import USTariffFraction

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

    try:
        with CoreSessionLocal() as session:
            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_us_tariff_fraction(
                    row_norm,
                    i,
                    actualizar=actualizar,
                    existing_fraction_codes=existing_fraction_codes,
                    valid_uom_codes=valid_uom_codes,
                    raw_row=row,
                )
                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_us_tariff_fraction_data(row_norm, tenant_id, company_id)
                if not data or not data.get("code"):
                    skipped_invalid += 1
                    skipped_details.append(
                        {
                            "line": i,
                            "reason": "FRACCION_ARANCELARIA vacío",
                            "solution": "Capturar en la columna FRACCION_ARANCELARIA una fracción arancelaria válida.",
                        }
                    )
                    continue

                existing = (
                    session.query(USTariffFraction)
                    .filter(
                        USTariffFraction.tenant_id == tenant_id,
                        USTariffFraction.company_id == company_id,
                        USTariffFraction.code == data["code"],
                    )
                    .first()
                )
                if existing:
                    data = row_to_us_tariff_fraction_data(
                        row_norm, tenant_id, company_id, existing=existing
                    )
                    existing.prefix = data.get("prefix")
                    existing.type_code = data.get("type_code")
                    existing.ad_valorem = data.get("ad_valorem")
                    existing.fixed_cost = data.get("fixed_cost")
                    existing.unit_of_measure = data.get("unit_of_measure")
                    existing.description = data.get("description")
                    session.add(existing)
                    updated_count += 1
                else:
                    new_row = USTariffFraction(**data)
                    session.add(new_row)
                    inserted_count += 1

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

    except Exception as e:
        logger.exception("FA 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:
        return {
            "status": "warning",
            "inserted": 0,
            "updated": 0,
            "skipped_invalid": skipped_invalid,
            "skipped_duplicate": 0,
            "skipped_missing_fk": 0,
            "skipped_details": skipped_details,
            "message": f"No se insertaron registros. {skipped_invalid} rechazados.",
        }
    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": 0,
            "skipped_missing_fk": 0,
            "skipped_details": skipped_details,
        }
    return {
        "status": "finished",
        "inserted": inserted_count,
        "updated": updated_count,
        "skipped_invalid": skipped_invalid,
        "skipped_duplicate": 0,
        "skipped_missing_fk": 0,
        "skipped_details": skipped_details,
    }


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