from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile

from recruitment import config, service
from recruitment.auth import verify_api_key
from recruitment.errors import RecruitmentError
from recruitment.schemas import JDGenerateRequest, JDGenerateResponse, ResumeParseResponse

router = APIRouter(
    prefix="/recruitment",
    tags=["Recruitment"],
    dependencies=[Depends(verify_api_key)],
)

_READ_CHUNK = 1024 * 1024


async def _read_capped(file: UploadFile, limit: int) -> bytes:
    """Reads the upload in chunks and aborts as soon as the cap is crossed, so
    an oversized file is rejected without buffering all of it first."""
    buf = bytearray()
    while chunk := await file.read(_READ_CHUNK):
        buf.extend(chunk)
        if len(buf) > limit:
            raise HTTPException(
                413, f"Resume exceeds the maximum size of {limit // (1024 * 1024)} MB"
            )
    return bytes(buf)


@router.post(
    "/parse-resume",
    response_model=ResumeParseResponse,
    summary="Extract structured candidate data from a PDF resume",
)
async def parse_resume(
    resume: UploadFile = File(..., description="Candidate resume, PDF only"),
    job_description: str = Form(..., description="Job description the resume is evaluated against"),
) -> ResumeParseResponse:
    content = await _read_capped(resume, config.MAX_RESUME_BYTES)
    try:
        return await service.parse_resume(resume.filename, content, job_description)
    except RecruitmentError as exc:
        raise HTTPException(status_code=exc.status_code, detail=exc.detail)


@router.post(
    "/generate-jd",
    response_model=JDGenerateResponse,
    summary="Generate a job description, salary range and interview questions for a role",
)
async def generate_jd(payload: JDGenerateRequest) -> JDGenerateResponse:
    try:
        return await service.generate_job_description(payload)
    except RecruitmentError as exc:
        raise HTTPException(status_code=exc.status_code, detail=exc.detail)
