"""
s19 - Showcase 4 site screenshots, then Thank you + QR + author block.

Two sub-slides: first a brief visual proof the site has way more than fits in
a talk (homepage, CVEs page, heap lab, paper reader), then the standard
Thank you / Questions slide with companion URL + QR code + GitHub repo.
"""

import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent.parent))

import numpy as np
from manim import (
    Text, ImageMobject, Rectangle, VGroup, Group, FadeIn,
    UP, DOWN, LEFT, RIGHT, ORIGIN,
)
from src.slides._core import SceneSlide
from src.slides._theme import SecurityPalette, Fonts, Sizes, Layout


COMPANION_URL = "https://mcs.danielwagner.ro"
GITHUB_URL = "github.com/danielw98/zero-click-exploit-analysis"

# Paths are resolved relative to project root (manim/../).
_PROJECT_ROOT = Path(__file__).resolve().parents[3]
_SCREENSHOT_DIR = _PROJECT_ROOT / "docs" / "screenshots"

# (image filename, caption shown under the thumbnail)
SHOWCASE_TILES = [
    ("home.png",         "Homepage"),
    ("cves.png",         "CVE breakdown"),
    ("heap-lab.png",     "Heap lab"),
    ("paper-reader.png", "Paper reader (IEEE)"),
]


def _make_qr_array(url: str, box_size: int = 12, border: int = 2) -> np.ndarray:
    """Build a numpy RGB array for the QR code so ImageMobject can render it."""
    import qrcode
    qr = qrcode.QRCode(
        version=None,
        error_correction=qrcode.constants.ERROR_CORRECT_M,
        box_size=box_size,
        border=border,
    )
    qr.add_data(url)
    qr.make(fit=True)
    img = qr.make_image(fill_color=(230, 237, 243), back_color=(13, 17, 23))
    img = img.convert("RGB")
    return np.array(img)


def _tile(image_path: Path, caption: str, *, w: float, h: float) -> Group:
    frame = Rectangle(
        width=w, height=h,
        fill_color=SecurityPalette.BG_PANEL, fill_opacity=0.45,
        stroke_color=SecurityPalette.RULE, stroke_width=1,
    )
    parts = [frame]
    if image_path.exists():
        img = ImageMobject(str(image_path))
        # Fit inside the frame while keeping aspect ratio. Leave room for
        # the caption (0.35) and a small inset (0.06 each side).
        img.set_width(w - 0.12)
        if img.height > h - 0.50:
            img.set_height(h - 0.50)
        img.move_to(frame.get_center() + np.array([0.0, 0.18, 0.0]))
        parts.append(img)
    cap = Text(caption, font=Fonts.MONO, font_size=Sizes.CAPTION - 4,
               color=SecurityPalette.FG_DIM)
    cap.move_to(frame.get_center() + np.array([0.0, -h / 2 + 0.20, 0.0]))
    parts.append(cap)
    return Group(*parts)


class S19ThankYou(SceneSlide):
    SECTION = None
    WITH_FOOTER = False
    ON_DARK = True

    def construct_content(self):
        # Thank you / QR layout (showcase sub-slide removed per request).
        thanks = Text(
            "Thank you.",
            font=Fonts.SERIF_DISPLAY, font_size=Sizes.TITLE_HUGE - 4,
            color=SecurityPalette.FG, weight="NORMAL",
        )
        thanks.move_to((-2.6, 1.8, 0))

        questions = Text(
            "Questions?",
            font=Fonts.SERIF, font_size=Sizes.TITLE - 4,
            color=SecurityPalette.WARN,
        )
        questions.next_to(thanks, DOWN, buff=0.40).align_to(thanks, LEFT)

        url_label = Text(
            "companion site:",
            font=Fonts.SANS, font_size=Sizes.BODY - 4,
            color=SecurityPalette.FG_MUTED, weight="MEDIUM",
        )
        url_label.move_to((-2.6, -0.6, 0)).align_to(thanks, LEFT)

        url_text = Text(
            "mcs.danielwagner.ro",
            font=Fonts.SANS, font_size=Sizes.SUBTITLE,
            color=SecurityPalette.INFO, weight="BOLD",
        )
        url_text.next_to(url_label, DOWN, buff=0.20).align_to(url_label, LEFT)

        url_extra = Text(
            "paper PDF / labs / resources / patches",
            font=Fonts.SANS, font_size=Sizes.CAPTION - 3,
            color=SecurityPalette.FG_MUTED,
        )
        url_extra.next_to(url_text, DOWN, buff=0.18).align_to(url_label, LEFT)

        repo_url = Text(
            "source: " + GITHUB_URL,
            font=Fonts.MONO, font_size=Sizes.CAPTION - 4,
            color=SecurityPalette.SAFE,
        )
        repo_url.next_to(url_extra, DOWN, buff=0.20).align_to(url_label, LEFT)

        authors_row1 = Text(
            "Stefan-Daniel WAGNER",
            font=Fonts.SANS, font_size=Sizes.BODY - 2,
            color=SecurityPalette.FG, weight="BOLD",
        )
        authors_row2 = Text(
            "Dan-Gabriel OLTEAN     -     Victor-Nicolae MATVEEV",
            font=Fonts.SANS, font_size=Sizes.SMALL,
            color=SecurityPalette.FG,
        )
        coord_line = Text(
            "Coordonator: conf. univ. dr. Emil Simion, FSA, UNSTPB - emil.simion@upb.ro",
            font=Fonts.SANS, font_size=Sizes.CAPTION - 4,
            color=SecurityPalette.FG_MUTED,
        )
        authors_block = VGroup(authors_row1, authors_row2, coord_line).arrange(
            DOWN, buff=0.15)
        authors_block.move_to((0.0, Layout.BOTTOM_EDGE + 0.85, 0))

        qr_array = _make_qr_array(COMPANION_URL)
        qr = ImageMobject(qr_array)
        qr.set_width(3.5)
        qr.move_to((3.6, 0.0, 0))

        qr_caption = Text(
            "scan to open",
            font=Fonts.SANS, font_size=Sizes.CAPTION,
            color=SecurityPalette.FG_MUTED,
        )
        qr_caption.next_to(qr, DOWN, buff=0.25)

        self.play(FadeIn(thanks, shift=0.2 * UP), run_time=0.7)
        self.play(FadeIn(questions, shift=0.2 * UP), run_time=0.5)
        self.play(FadeIn(url_label), FadeIn(url_text), FadeIn(url_extra), run_time=0.6)
        self.play(FadeIn(repo_url), run_time=0.4)
        self.play(FadeIn(qr), FadeIn(qr_caption), run_time=0.6)
        self.play(FadeIn(authors_block), run_time=0.5)
        self.wait(2.0)
