from fastapi import APIRouter, UploadFile, File, Form, Depends
from app.tasks.ingest import process_pdf
from app.db.session import get_db
from app.db.models import UploadJob
import shutil, os, uuid

router = APIRouter(prefix="/api")

@router.post("/upload")
async def upload(file: UploadFile = File(...),
                 newspaper: str = Form(...), edition: str = Form("Main"),
                 date: str = Form(...), db=Depends(get_db)):
    path = f"/data/storage/{uuid.uuid4().hex}_{file.filename}"
    os.makedirs("/data/storage", exist_ok=True)
    with open(path, "wb") as f:
        shutil.copyfileobj(file.file, f)
        
    job = UploadJob(filename=file.filename, newspaper=newspaper, edition=edition, date=date)
    db.add(job)
    db.commit()
    db.refresh(job)
    
    task = process_pdf.delay(job.id, path, newspaper, edition, date)
    
    job.celery_task_id = task.id
    db.commit()
    
    return {"job_id": job.id, "task_id": task.id, "status": "queued"}

@router.get("/jobs")
def get_jobs(db=Depends(get_db)):
    jobs = db.query(UploadJob).order_by(UploadJob.created_time.desc()).all()
    return jobs

@router.get("/status/{task_id}")
def status(task_id: str):
    from app.tasks.celery_app import celery
    res = celery.AsyncResult(task_id)
    return {"state": res.state, "info": res.info}
