"""Celery tasks for import validation."""
from __future__ import annotations
import logging

from celery import shared_task

logger = logging.getLogger(__name__)


@shared_task(name="imports.validate_excel_import", queue="step_processing", bind=True)
def validate_excel_import(self, validation_id: str, excel_path: str, tenant_id: str | None = None):
    """Run sanity check on imported Excel file and store results."""
    logger.info("Running import validation %s for %s", validation_id, excel_path)
    try:
        from app.domains.imports.service import run_sanity_check
        result = run_sanity_check(validation_id, excel_path, tenant_id)
        logger.info("Validation %s completed: %s", validation_id, result.get("summary", {}))
        return result
    except Exception as exc:
        logger.error("Validation %s failed: %s", validation_id, exc)
        # Mark as failed in DB
        try:
            from sqlalchemy import create_engine
            from sqlalchemy.orm import Session
            from app.config import settings as app_settings
            from app.domains.imports.models import ImportValidation
            from datetime import datetime
            sync_url = app_settings.database_url.replace("+asyncpg", "")
            engine = create_engine(sync_url)
            with Session(engine) as db:
                val = db.get(ImportValidation, validation_id)
                if val:
                    val.status = "failed"
                    val.completed_at = datetime.utcnow()
                    db.commit()
        except Exception:
            pass
        raise
