# Requires fastapi pytest httpx python-multipart tabulate

import csv
import io
from collections import defaultdict
from fastapi import FastAPI, File, HTTPException, UploadFile
from tabulate import tabulate

app = FastAPI()

@app.post("/upload-csv/")
async def upload_and_summarize_csv(file: UploadFile = File(...)):
    if not file.filename.endswith(".csv"):
        raise HTTPException(status_code=400, detail="Only CSV files are allowed.")

    # Read and decode uploaded file
    contents = await file.read()
    decoded_text = contents.decode("utf-8")
    reader = csv.DictReader(io.StringIO(decoded_text))

    # Process data: aggregate revenue by category
    category_totals = defaultdict(float)
    row_count = 0
    try:
        for row in reader:
            category = row["category"].strip()
            amount = float(row["amount"])
            category_totals[category] += amount
            row_count += 1
    except (KeyError, ValueError) as exc:
        raise HTTPException(status_code=422, detail=f"Invalid CSV format: {exc}")

    # Format and print tabulated summary
    table_data = [[cat, f"${total:.2f}"] for cat, total in category_totals.items()]
    summary_table = tabulate(table_data, headers=["Category", "Total Sales"], tablefmt="grid")
    print(summary_table)

    return {
        "filename": file.filename,
        "rows_processed": row_count,
        "summary": dict(category_totals),
    }

