from app.tasks.worker import celery_app


@celery_app.task(bind=True)
def train_ml_model_task(self, model_name: str = None, algorithm: str = "logistic_regression"):
    from app.core.database import SessionLocal
    from app.services.ml_service import train_model

    db = SessionLocal()
    try:
        self.update_state(state="PROGRESS", meta={"message": "Fetching training data"})
        mv = train_model(db, model_name=model_name, algorithm=algorithm)
        if mv:
            return {
                "status": "completed",
                "model_id": mv.id,
                "name": mv.name,
                "accuracy": mv.accuracy,
                "train_samples": mv.train_samples,
            }
        else:
            return {"status": "failed", "reason": "Not enough training data (need >= 20 samples)"}
    except Exception as e:
        return {"status": "failed", "reason": str(e)}
    finally:
        db.close()
