from fastapi import FastAPI, HTTPException
import qrcode
from io import BytesIO
import base64
from pydantic import BaseModel

app = FastAPI(title="wtihub-Pixel Media Engine")

class QRRequest(BaseModel):
    url: str

@app.get("/health")
def health_check():
    return {"status": "online", "engine": "wtihub-pixel-python"}

@app.post("/generate-qr")
async def generate_qr(request: QRRequest):
    """
    wtihub-QR Logic:
    Takes a URL and returns a Base64 encoded QR image.
    """
    url_to_encode = request.url

    try:
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qr.add_data(url_to_encode)
        qr.make(fit=True)

        img = qr.make_image(fill_color="#074435", back_color="#0E1117")

        buffered = BytesIO()
        img.save(buffered, format="PNG")

        img_base64 = base64.b64encode(buffered.getvalue()).decode()

        return {
            "wtihub_qr_base64": f"data:image/png;base64,{img_base64}",
            "original_target": url_to_encode
        }
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"wtihub-pixel-error: ${str(e)}")