"""Flask app for mcs.danielwagner.ro - Zero-Click, Old Tricks."""

import sys
from pathlib import Path
from flask import Flask, Response, abort, flash, redirect, render_template, send_from_directory, url_for

WEB_DIR = Path(__file__).parent
ARTICLE_DIR = WEB_DIR.parent / "article"
DOWNLOADS_DIR = WEB_DIR / "static" / "downloads"
SECTIONS_DIR = WEB_DIR / "static" / "sections"
GENERATED_DIR = WEB_DIR / "static" / "generated"

sys.path.insert(0, str(WEB_DIR))

SECTIONS = [
    {"slug": "introduction", "number": "I",   "title": "Introduction",
     "blurb": "Why zero-click chains matter and what the 2025 case reveals."},
    {"slug": "background",   "number": "II",  "title": "Background",
     "blurb": "The C memory model, CWE classes, iOS media pipeline, FORCEDENTRY precedent."},
    {"slug": "methodology",  "number": "III", "title": "Methodology",
     "blurb": "CVE selection, analysis framework, Phoenix heap-two pedagogical bridge."},
    {"slug": "case_study",   "number": "IV",  "title": "Case Study",
     "blurb": "The 2025 chain: delivery (CVE-2025-55177) and exploitation (CVE-2025-43300)."},
    {"slug": "discussion",   "number": "V",   "title": "Discussion",
     "blurb": "Why mitigations failed, sandbox escape, structural alternatives."},
    {"slug": "conclusion",   "number": "VI",  "title": "Conclusion",
     "blurb": "Findings and recommendations."},
]

app = Flask(__name__)
app.secret_key = "scss-2026-zero-click"  # required for flash()


def _rebuild_if_stale(slug: str) -> None:
    tex = ARTICLE_DIR / f"{slug}.tex"
    fragment = SECTIONS_DIR / f"{slug}.html"
    if tex.exists() and (
        not fragment.exists() or tex.stat().st_mtime > fragment.stat().st_mtime
    ):
        try:
            from build_sections import build_one
            SECTIONS_DIR.mkdir(parents=True, exist_ok=True)
            build_one(slug)
        except Exception as exc:
            app.logger.warning("auto-rebuild failed for %s: %s", slug, exc)


@app.route("/")
def index():
    return render_template("index.html")


@app.route("/chain")
def attack():
    return render_template("attack.html")


@app.route("/cves")
def cves():
    return render_template("cves.html")


@app.route("/heap-lab")
def heap_two():
    return render_template("heap_two.html")


@app.route("/stack-lab")
def stack_lab():
    return render_template("stack_lab.html")


@app.route("/patches")
def patches():
    return render_template("patches.html")


@app.route("/paper/")
def paper_index():
    return render_template("paper_index.html", sections=SECTIONS)


@app.route("/paper/<slug>/")
def paper_section(slug: str):
    idx = next((i for i, s in enumerate(SECTIONS) if s["slug"] == slug), None)
    if idx is None:
        abort(404)

    _rebuild_if_stale(slug)

    fragment_path = SECTIONS_DIR / f"{slug}.html"
    fragment = fragment_path.read_text(encoding="utf-8") if fragment_path.exists() else None

    section = SECTIONS[idx]
    prev_section = SECTIONS[idx - 1] if idx > 0 else None
    next_section = SECTIONS[idx + 1] if idx < len(SECTIONS) - 1 else None

    return render_template(
        "paper_section.html",
        section=section,
        fragment=fragment,
        prev_section=prev_section,
        next_section=next_section,
    )


@app.route("/paper/download")
def paper_download():
    return send_from_directory(DOWNLOADS_DIR, "zero-click-old-tricks.pdf",
                               mimetype="application/pdf",
                               as_attachment=False,
                               download_name="zero-click-old-tricks.pdf")



@app.route("/resources")
def resources():
    return render_template("resources.html")


@app.route("/team")
def team():
    return render_template("team.html")


# ---------------------------------------------------------------------------
# Hidden routes for the Manim deck (not linked from any navigation).
# Built by:   cd manim && python -m src.slides           (HQ -> /slides)
#             cd manim && python -m src.slides --preview (LQ -> /slides-dev)
# ---------------------------------------------------------------------------

def _serve_revealjs_bundle(html_path: Path, rebuild_hint: str) -> Response:
    if not html_path.exists():
        flash(f"Deck-ul nu a fost generat. Build: {rebuild_hint}")
        return redirect(url_for("index"))
    html = html_path.read_text(encoding="utf-8")
    favicon_url = url_for("static", filename="favicon.svg")
    inject = (
        f'<link rel="icon" type="image/svg+xml" href="{favicon_url}">\n'
        f'<title>Memory Vulnerabilities - Exploit zero-click: WhatsApp-ImageIO 2025</title>\n'
    )
    html = html.replace("<head>", "<head>\n" + inject, 1)
    return Response(html, mimetype="text/html; charset=utf-8")


@app.route("/slides")
def slides():
    """HQ Manim deck (revealjs bundle)."""
    return _serve_revealjs_bundle(
        GENERATED_DIR / "write-primitive-exploits-2026.html",
        rebuild_hint="cd manim && python -m src.slides",
    )


@app.route("/slides-dev")
def slides_dev():
    """Dev / low-quality deck. Same UI, faster iteration."""
    return _serve_revealjs_bundle(
        GENERATED_DIR / "write-primitive-exploits-2026-dev.html",
        rebuild_hint="cd manim && python -m src.slides --preview",
    )


@app.route("/slides/prezentare")
def slides_prezentare():
    """Hidden presenter notes: 10-min verbal script mapped onto the 27 pptx slides."""
    return render_template("prezentare.html")


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=True)
