from __future__ import annotations

from license_receipt import assert_local_receipt_or_die

assert_local_receipt_or_die()

import lev_server
from actions_runtime import install as install_actions
from fastapi import Request
from pydantic import BaseModel
from media_runtime import normalize_data_uri_for_vision


def _levbot_deploy_remove_route(app, path: str, method: str) -> None:
    app.router.routes = [
        route
        for route in app.router.routes
        if not (getattr(route, "path", None) == path and method in getattr(route, "methods", set()))
    ]


class DeployChatIn(BaseModel):
    chat_id: str
    text: str = ""
    image_url: str = ""


app = install_actions(lev_server)
try:
    from privacy_runtime import install as install_privacy
except ModuleNotFoundError:
    install_privacy = None
if install_privacy is not None:
    app = install_privacy(lev_server)

_levbot_deploy_remove_route(app, "/chat", "POST")

@app.post("/chat")
async def levbot_deploy_chat(inp: DeployChatIn):
    image_uri = ""
    if inp.image_url:
        try:
            image_uri, detected_mime, normalized_mime, source_bytes, normalized_bytes = normalize_data_uri_for_vision(inp.image_url)
            print(
                "SITE IMAGE OK",
                "detected_mime=" + detected_mime,
                "normalized_mime=" + normalized_mime,
                "bytes=" + str(source_bytes),
                "normalized_bytes=" + str(normalized_bytes),
                flush=True,
            )
        except Exception as exc:
            print("SITE IMAGE FAILED", type(exc).__name__, flush=True)
            image_uri = ""
    reply = await lev_server.turn(inp.chat_id, inp.text, image_uri)
    clean, slugs = lev_server.extract_cards(reply)
    return {"reply": clean, "cards": [f"{lev_server.CARD_BASE_URL}/{lev_server.card_path(s).name}" for s in slugs if lev_server.card_path(s)]}

try:
    from avito_runtime import install as install_avito
except ModuleNotFoundError:
    install_avito = None
if install_avito is not None:
    app = install_avito(lev_server)
