# New file: api/v2/jobs_async.py
from fastapi import APIRouter, Depends, BackgroundTasks, UploadFile, File
from typing import Optional, Dict, Any
import uuid
from ...models import Job, JobStatus
from ...auth import get_current_account
from ...db import get_session
from ...storage import get_storage_backend

router = APIRouter(prefix="/api/v2/jobs", tags=["Jobs V2"])


def estimate_time(size_bytes: int) -> int:
    """Rough ETA in seconds based on upload size."""
    return max(10, int(size_bytes / (1024 * 1024) * 5))


@router.post("/dedupe", status_code=202)
async def submit_dedupe_async(
    file: UploadFile = File(...),
    threshold: int = 80,
    webhook_url: Optional[str] = None,
    background_tasks: BackgroundTasks = None,
    account_id: str = Depends(get_current_account),
) -> Dict[str, Any]:
    """
    Async dedupe submission with immediate 202 response.
    """
    job_id = str(uuid.uuid4())

    # Store file to S3/storage
    storage = get_storage_backend()
    file_key = f"{account_id}/inputs/{job_id}/{file.filename}"
    file_url = await storage.save(file, file_key)

    # Create job record
    job = Job(
        id=job_id,
        account_id=account_id,
        type="dedupe",
        status=JobStatus.QUEUED,
        config={
            "source_url": file_url,
            "threshold": threshold,
            "webhook_url": webhook_url,
        },
    )

    # Save to DB
    async with get_session() as db:
        db.add(job)
        await db.commit()

    # Queue the job
    from ...worker import conn
    from rq import Queue

    q = Queue("default", connection=conn)
    q.enqueue("fmatch.saas.worker.run_matching_job", job_id, job_timeout="1h")

    return {
        "job_id": job_id,
        "status": "queued",
        "progress_url": f"/api/v1/jobs/{job_id}/progress",
        "status_url": f"/api/v1/jobs/{job_id}/status",
        "estimated_time_seconds": estimate_time(file.size),
    }


@router.delete("/{job_id}")
async def cancel_job(
    job_id: str, account_id: str = Depends(get_current_account)
) -> Dict[str, str]:
    """Cancel a running job"""
    # Implementation here
    pass
