"""Pip's World: a small Flask app that serves the animation.

The animation runs in the visitor's browser (Remotion Player, prebuilt into
static/player.js), so the server only hands out a page and static files.
Hosting needs Python only; Node.js is needed only to rebuild the animation.
"""

import hashlib
import os
from pathlib import Path

from flask import Flask, render_template, send_from_directory

STATIC_DIR = Path(__file__).resolve().parent / "static"

app = Flask(__name__)
# Asset URLs carry a content hash (see asset_version), so browsers can cache for a week.
app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 60 * 60 * 24 * 7


def _content_hash(*names: str) -> str:
    digest = hashlib.sha256()
    for name in names:
        digest.update((STATIC_DIR / name).read_bytes())
    return digest.hexdigest()[:12]


ASSET_VERSION = _content_hash("player.js", "poster.jpg")


@app.context_processor
def inject_asset_version():
    return {"asset_version": ASSET_VERSION}


@app.after_request
def security_headers(response):
    response.headers.setdefault("X-Content-Type-Options", "nosniff")
    response.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin")
    return response


@app.get("/")
def index():
    return render_template("index.html", embed=False)


@app.get("/embed")
def embed():
    """Just the player, sized to the window. Use it inside an <iframe>."""
    return render_template("index.html", embed=True)


@app.get("/download")
def download():
    return send_from_directory(STATIC_DIR, "pips-world.mp4", as_attachment=True, download_name="pips-world.mp4")


@app.get("/healthz")
def healthz():
    return {"status": "ok"}


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "5000")))
