from fastapi import FastAPI, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
import fitz
from collections import Counter
from typing import List

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

def fmt_rgb(r,g,b):
    return f"rgb({r},{g},{b})"

@app.post("/analyze")
async def analyze(files: List[UploadFile] = File(...)):
    results = []

    for f in files:
        name = f.filename
        ext = name.split(".")[-1].lower()

        data = await f.read()

        if ext == "pdf":
            doc = fitz.open(stream=data, filetype="pdf")

            raster_present = False
            vector_present = False
            color_counter = Counter()

            for page in doc:
                if page.get_images(full=True):
                    raster_present = True

                drawings = page.get_drawings()
                if drawings:
                    vector_present = True

                for d in drawings:
                    col = d.get("fill") or d.get("color")
                    if col and isinstance(col, (tuple, list)) and len(col) >= 3:
                        r,g,b = [round(v*255) for v in col[:3]]
                        color_counter[fmt_rgb(r,g,b)] += 1

            top_colors = [c for c,_ in color_counter.most_common(10)]

            status = "PASS"
            notes = []

            if raster_present:
                status = "FAIL"
                notes.append("Raster images detected.")

            results.append({
                "file": name,
                "type": "PDF",
                "vector_present": vector_present,
                "raster_present": raster_present,
                "color_spaces": ["RGB"],
                "color_values_top": top_colors,
                "status": status,
                "notes": notes
            })

        else:
            results.append({
                "file": name,
                "type": ext.upper(),
                "vector_present": None,
                "raster_present": None,
                "color_spaces": ["N/A"],
                "color_values_top": [],
                "status": "REVIEW",
                "notes": ["Upload PDF export for analysis."]
            })

    return {"results": results}