from __future__ import annotations

import os
import hashlib
from uuid import uuid4
from pathlib import Path
from fastapi import APIRouter, Request, Response
from fastapi.responses import JSONResponse

router = APIRouter(prefix="/api/v1/uploads", tags=["uploads"])

MAX_DEV_UPLOAD = 10 * 1024 * 1024  # 10 MB guard to avoid accidental huge posts


def _upload_dir() -> Path:
    # Default to /tmp; allow override for Windows via env
    default = r"/tmp/fm_uploads" if os.name != "nt" else r"C:\\temp\\fm_uploads"
    p = Path(os.getenv("FM_UPLOAD_DIR", default))
    p.mkdir(parents=True, exist_ok=True)
    return p


@router.post("")  # This handles both /api/v1/uploads and /api/v1/uploads/
async def upload_csv(request: Request):
    """Accept raw CSV bytes and persist to a local folder for dev usage.
    Returns a file:// storage_key usable by the async worker.
    """
    body = await request.body()
    if not body:
        return Response(
            content='{"error":"empty body"}',
            status_code=400,
            media_type="application/json",
        )
    if len(body) > MAX_DEV_UPLOAD:
        return Response(
            content='{"error":"too_large"}',
            status_code=413,
            media_type="application/json",
        )

    h = hashlib.sha256(body).hexdigest()[:12]
    filename = f"{uuid4()}-{h}.csv"
    out = _upload_dir() / filename
    out.write_bytes(body)

    # Return clean basename key and absolute path for debugging
    return JSONResponse(
        {
            "ok": True,
            "storage_key": out.name,
            "abs_path": str(out.resolve()),
            "bytes": len(body),
            "sha256_12": h,
        }
    )
