from celery import Celery
from typing import List, Dict, Optional
from dependencies.HybridSearch import HybridSearch
import db_config.database as dbase
from db_config.models import Documents
from sqlalchemy.orm import Session

celery_app = Celery(
    "tasks",
    broker="redis://localhost:6379/0",  # Redis as message broker
    backend="redis://localhost:6379/0"
)

@celery_app.task
def process_document_celery(
    document_path: str,
    document_name: str,
    sanitized_name: str,
    document_url: str,
    upload_dir: str,
    metadata: Dict[str, str],
    user_code: str,
    collection_name: str,
    folder_name: str,
    doc_id: int
) -> str:
    db: Session = dbase.SessionLocal()
    try:
        # Initialize HybridSearch
        hs = HybridSearch(collection_name, user_code, folder_name)
        
        # Process the document
        hs.upsert_document(document_path, document_name, sanitized_name, None, metadata, upload_dir)
        document_uuid = hs.get_document_uuid(sanitized_name)

        # Fetch document from DB
        update_status = db.query(Documents).filter(Documents.doc_id == doc_id).first()
        print(update_status)
        if update_status:
            update_status.doc_url = document_url
            update_status.document_uuid = document_uuid
            update_status.doc_status = "Ready"
            db.commit()
            db.refresh(update_status)
        else:
            return f"Document with doc_id {doc_id} not found."

    except Exception as e:
        db.rollback()  # Rollback in case of an error
        return f"Error processing document: {str(e)}"

    finally:
        db.close()  # Ensure the session is closed properly

    return "Document processed successfully."