import os
import tempfile
from pathlib import Path

from fastapi import APIRouter, File, HTTPException, UploadFile

from backend.services.import_service import import_file, import_from_statements_dir

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


@router.post("/upload")
async def upload_statement(file: UploadFile = File(...)):
    if not file.filename or not file.filename.lower().endswith(".pdf"):
        raise HTTPException(status_code=400, detail="Only PDF files are allowed")
    if not (file.filename.startswith("Т-") or file.filename.startswith("С-") or file.filename.startswith("Я-")):
        raise HTTPException(status_code=400, detail="Поддерживаются выписки Т-, С- и Я-банка (Т/С/Я-MM-YY.pdf)")
    suffix = Path(file.filename).suffix
    with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
        content = await file.read()
        tmp.write(content)
        tmp_path = tmp.name
    try:
        added, skipped, parsed = import_file(tmp_path, file.filename)
        return {"added": added, "skipped_duplicates": skipped, "parsed": parsed, "filename": file.filename}
    finally:
        os.unlink(tmp_path)


@router.post("/from-folder")
def import_from_folder():
    added, skipped, parsed = import_from_statements_dir()
    return {"added": added, "skipped_duplicates": skipped, "parsed": parsed}
