#!/usr/bin/env python
"""Cron entry point for InMotion cPanel (no background workers on shared hosting).

Configure a cPanel Cron Job to run this every few minutes, e.g.:
    */5 * * * * /home/<cpaneluser>/virtualenv/memodoc/3.x/bin/python \
        /home/<cpaneluser>/memodoc/scripts/process_pending_documents.py >> \
        /home/<cpaneluser>/memodoc/logs/process_documents.log 2>&1
"""
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app import create_app
from app.extensions import db
from app.models import Document, Patient
from app.processing.pipeline import process_document, regenerate_summary

BATCH_SIZE = 10


def main():
    app = create_app()
    with app.app_context():
        pending = (
            Document.query.filter_by(status=Document.STATUS_PENDING)
            .order_by(Document.uploaded_at.asc())
            .limit(BATCH_SIZE)
            .all()
        )

        if not pending:
            print("No hay documentos pendientes.")
            return

        patients_to_refresh = set()

        for document in pending:
            print(f"Procesando documento {document.id} ({document.original_filename})...")
            process_document(document)
            db.session.commit()

            if document.status == Document.STATUS_DONE:
                patients_to_refresh.add(document.patient_id)
            else:
                print(f"  -> error: {document.error_message}")

        for patient_id in patients_to_refresh:
            patient = db.session.get(Patient, patient_id)
            regenerate_summary(patient)
            db.session.commit()
            print(f"Resumen actualizado para paciente {patient_id}.")


if __name__ == "__main__":
    main()
