"""
s08 - CENTERPIECE: stack smashing, byte by byte.

Mirrors the website's /stack-lab visualization (web/static/js/pages/stack-lab.js):
two terminal-style panels, MEMORY (x/10gx $rsp) on top and gdb session on
bottom. State badge (SAFE / HIJACKED) tracks corruption of saved RIP.

5 next_slide() boundaries:
  0: initial state    (gdb stops just before gets(); frame clean)
  1: "A"*16           (benign, first row of buffer filled)
  2: "A"*72           (saved RBP corrupted, RIP intact)
  3: "A"*80           (RBP + RIP both corrupted)
  4: hijack payload   (RBP = "B"*8, RIP = &complete_level)
  5: ret              (Congratulations, win)
"""

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

import numpy as np
from manim import (
    Text, RoundedRectangle, VGroup, FadeIn, FadeOut, Write, ReplacementTransform,
    AnimationGroup, Indicate, Flash,
    UP, DOWN, LEFT, RIGHT, ORIGIN,
)
from src.slides._core import SceneSlide
from src.slides._theme import SecurityPalette, Fonts, Sizes, Layout
from src.slides._layout import slide_title, terminal_panel


RBP_DEFAULT = "0x00007fffffffdc90"
RIP_DEFAULT = "0x0000555555555230"
COMPLETE    = "0x000055555555518a"
Z           = "0x0000000000000000"
A           = "0x4141414141414141"
B           = "0x4242424242424242"

ADDRS = [
    "0x7fffffffdc30:",
    "0x7fffffffdc40:",
    "0x7fffffffdc50:",
    "0x7fffffffdc60:",
    "0x7fffffffdc70:",
]


def _mem_rows_for_step(step: int):
    """Return list of 5 tuples: (addr, q1, q1_state, q2, q2_state, label, label_state)."""
    # state in: "default" (FG_MUTED), "ok" (FG), "changed" (SAFE green),
    #           "overflow" (DANGER red), "hijack" (WARN amber)
    if step == 0:
        return [
            (ADDRS[0], Z,           "default", Z,           "default", "# buffer[0..15]",                "dim"),
            (ADDRS[1], Z,           "default", Z,           "default", "# buffer[16..31]",               "dim"),
            (ADDRS[2], Z,           "default", Z,           "default", "# buffer[32..47]",               "dim"),
            (ADDRS[3], Z,           "default", Z,           "default", "# buffer[48..63]",               "dim"),
            (ADDRS[4], RBP_DEFAULT, "ok",      RIP_DEFAULT, "ok",      "# saved RBP + saved return",     "dim"),
        ]
    if step == 1:  # 16 bytes
        return [
            (ADDRS[0], A,           "changed", A,           "changed", "# buffer[0..15]",                "dim"),
            (ADDRS[1], Z,           "default", Z,           "default", "# buffer[16..31]",               "dim"),
            (ADDRS[2], Z,           "default", Z,           "default", "# buffer[32..47]",               "dim"),
            (ADDRS[3], Z,           "default", Z,           "default", "# buffer[48..63]",               "dim"),
            (ADDRS[4], RBP_DEFAULT, "ok",      RIP_DEFAULT, "ok",      "# saved RBP + saved return",     "dim"),
        ]
    if step == 2:  # 72 bytes -> RBP corrupted
        return [
            (ADDRS[0], A,           "changed",  A,           "changed",  "# buffer[0..15]",              "dim"),
            (ADDRS[1], A,           "changed",  A,           "changed",  "# buffer[16..31]",             "dim"),
            (ADDRS[2], A,           "changed",  A,           "changed",  "# buffer[32..47]",             "dim"),
            (ADDRS[3], A,           "changed",  A,           "changed",  "# buffer[48..63]",             "dim"),
            (ADDRS[4], A,           "overflow", RIP_DEFAULT, "ok",       "# saved RBP corrupted",        "warn"),
        ]
    if step == 3:  # 80 bytes -> both corrupted
        return [
            (ADDRS[0], A,           "changed",  A,           "changed",  "# buffer[0..15]",              "dim"),
            (ADDRS[1], A,           "changed",  A,           "changed",  "# buffer[16..31]",             "dim"),
            (ADDRS[2], A,           "changed",  A,           "changed",  "# buffer[32..47]",             "dim"),
            (ADDRS[3], A,           "changed",  A,           "changed",  "# buffer[48..63]",             "dim"),
            (ADDRS[4], A,           "overflow", A,           "overflow", "# saved return CORRUPTED",     "danger"),
        ]
    # step 4 or 5: hijack
    return [
        (ADDRS[0], A,           "changed",  A,           "changed",  "# buffer[0..15]",              "dim"),
        (ADDRS[1], A,           "changed",  A,           "changed",  "# buffer[16..31]",             "dim"),
        (ADDRS[2], A,           "changed",  A,           "changed",  "# buffer[32..47]",             "dim"),
        (ADDRS[3], A,           "changed",  A,           "changed",  "# buffer[48..63]",             "dim"),
        (ADDRS[4], B,           "overflow", COMPLETE,    "hijack",   "# RIP -> &complete_level",     "warn"),
    ]


def _gdb_lines_for_step(step: int):
    """Return list of (prompt, body, color_kind)."""
    if step == 0:
        return [
            ("(gdb)", "break *start_level+15",                                        "cmd"),
            ("(gdb)", "run",                                                          "cmd"),
            ("",      "Breakpoint 1, start_level () at stack-four.c:11",              "dim"),
            ("",      "Stopped just before gets().  Frame laid out at $rsp.",         "dim"),
        ]
    if step == 1:
        return [
            ("(gdb)", "continue",                                                     "cmd"),
            (">",     '"A" * 16',                                                     "in"),
            ("",      "Program received input; stepping through gets()...",           "dim"),
            ("(gdb)", "x/gx $rbp+0x8",                                                "cmd"),
            ("",      "0x7fffffffdc78:  0x0000555555555230   # return address intact","ok"),
        ]
    if step == 2:
        return [
            ("(gdb)", "continue",                                                     "cmd"),
            (">",     '"A" * 72',                                                     "in"),
            ("(gdb)", "x/gx $rbp+0x8",                                                "cmd"),
            ("",      "0x7fffffffdc78:  0x0000555555555230   # RIP safe (RBP gone)",  "warn"),
        ]
    if step == 3:
        return [
            ("(gdb)", "continue",                                                     "cmd"),
            (">",     '"A" * 80',                                                     "in"),
            ("(gdb)", "x/gx $rbp+0x8",                                                "cmd"),
            ("",      "0x7fffffffdc78:  0x4141414141414141   # saved return CORRUPTED","danger"),
        ]
    if step == 4:
        return [
            ("(gdb)", "continue",                                                     "cmd"),
            (">",     '"A"*64 + "B"*8 + p64(&complete_level)',                        "in"),
            ("(gdb)", "x/gx $rbp+0x8",                                                "cmd"),
            ("",      "0x7fffffffdc78:  0x000055555555518a   -> &complete_level()",   "warn"),
        ]
    # step 5: ret
    return [
        ("(gdb)", "stepi",                                                            "cmd"),
        ("",      "complete_level () at stack-four.c:3",                              "ok"),
        ("",      "Congratulations, you've finished!     # ret2win",                  "win"),
    ]


STATE_COLOR = {
    "default":  None,  # set at runtime to FG_DIM
    "ok":       None,
    "changed":  None,
    "overflow": None,
    "hijack":   None,
    "dim":      None,
    "warn":     None,
    "danger":   None,
}


def _mem_state_color(kind):
    return {
        "default":  SecurityPalette.FG_DIM,
        "ok":       SecurityPalette.SAFE,
        "changed":  SecurityPalette.SAFE,
        "overflow": SecurityPalette.DANGER,
        "hijack":   SecurityPalette.WARN,
    }[kind]


def _mem_label_color(kind):
    return {
        "dim":    SecurityPalette.FG_DIM,
        "warn":   SecurityPalette.WARN,
        "danger": SecurityPalette.DANGER,
    }[kind]


def _gdb_body_color(kind):
    return {
        "cmd":    SecurityPalette.SAFE,
        "in":     SecurityPalette.FG,
        "dim":    SecurityPalette.FG_DIM,
        "ok":     SecurityPalette.FG,
        "warn":   SecurityPalette.WARN,
        "danger": SecurityPalette.DANGER,
        "win":    SecurityPalette.SAFE,
    }[kind]


def _build_mem_content(step: int) -> VGroup:
    rows = _mem_rows_for_step(step)
    row_mobs = []
    for addr, q1, q1s, q2, q2s, label, ls in rows:
        addr_t = Text(addr, font=Fonts.MONO, font_size=18,
                      color=SecurityPalette.SAFE, weight="MEDIUM")
        q1_t = Text(q1, font=Fonts.MONO, font_size=18,
                    color=_mem_state_color(q1s),
                    weight=("BOLD" if q1s in ("overflow", "hijack") else "MEDIUM"))
        q2_t = Text(q2, font=Fonts.MONO, font_size=18,
                    color=_mem_state_color(q2s),
                    weight=("BOLD" if q2s in ("overflow", "hijack") else "MEDIUM"))
        label_t = Text(label, font=Fonts.MONO, font_size=18,
                       color=_mem_label_color(ls),
                       weight=("BOLD" if ls != "dim" else "MEDIUM"))
        row = VGroup(addr_t, q1_t, q2_t, label_t).arrange(RIGHT, buff=0.40)
        row_mobs.append(row)
    return VGroup(*row_mobs).arrange(DOWN, buff=0.12, aligned_edge=LEFT)


def _build_gdb_content(step: int) -> VGroup:
    lines = _gdb_lines_for_step(step)
    line_mobs = []
    for prompt, body, kind in lines:
        if prompt == "(gdb)":
            prompt_t = Text(prompt, font=Fonts.MONO, font_size=18,
                            color=SecurityPalette.WARN, weight="BOLD")
        elif prompt == ">":
            prompt_t = Text(prompt, font=Fonts.MONO, font_size=18,
                            color=SecurityPalette.INFO, weight="BOLD")
        else:
            # No prompt: indent the body line with a transparent placeholder
            prompt_t = Text("     ", font=Fonts.MONO, font_size=18,
                            color=SecurityPalette.BG, weight="MEDIUM")
        body_t = Text(body, font=Fonts.MONO, font_size=18,
                      color=_gdb_body_color(kind),
                      weight=("BOLD" if kind in ("win", "danger") else "MEDIUM"))
        line = VGroup(prompt_t, body_t).arrange(RIGHT, buff=0.30, aligned_edge=UP * 0)
        line_mobs.append(line)
    return VGroup(*line_mobs).arrange(DOWN, buff=0.14, aligned_edge=LEFT)


def _state_badge(hijacked: bool) -> VGroup:
    color = SecurityPalette.DANGER if hijacked else SecurityPalette.SAFE
    bg = RoundedRectangle(
        corner_radius=0.08, width=1.6, height=0.46,
        fill_color=color, fill_opacity=0.30,
        stroke_color=color, stroke_width=1.5,
    )
    label = Text("HIJACKED" if hijacked else "SAFE",
                 font=Fonts.SANS, font_size=Sizes.CAPTION,
                 color=color, weight="BOLD")
    label.move_to(bg.get_center())
    return VGroup(bg, label)


def _place_in_panel(content: VGroup, panel: VGroup,
                    left_pad: float = 0.40, top_pad: float = 0.80):
    """Move content so its top-left aligns with panel inner top-left."""
    frame = panel[0]
    tl = frame.get_corner([-1, 1, 0])
    target_x = tl[0] + left_pad + content.width / 2
    target_y = tl[1] - top_pad - content.height / 2
    content.move_to((target_x, target_y, 0))


class S08Overflow(SceneSlide):
    SECTION = None
    WITH_FOOTER = True
    ON_DARK = True

    def construct_content(self):
        self.skip_reversing = True

        title = slide_title(
            "Stack smashing, byte by byte",
            font_size=Sizes.TITLE - 14, with_accent_rule=True,
        )
        title.move_to((-2.5, 3.30, 0.0))

        badge_safe = _state_badge(hijacked=False)
        badge_safe.move_to((5.3, 3.30, 0.0))
        badge_danger = _state_badge(hijacked=True)
        badge_danger.move_to((5.3, 3.30, 0.0))

        # MEMORY panel - upper half
        mem_panel = terminal_panel(
            "Memory", width=13.6, height=2.65,
            header_extra="x/10gx $rsp",
        )
        mem_panel.move_to((0.0, 1.20, 0.0))

        # GDB SESSION panel - lower half
        gdb_panel = terminal_panel(
            "gdb session", width=13.6, height=2.75,
        )
        gdb_panel.move_to((0.0, -1.95, 0.0))

        # Step 0 (initial)
        mem_v0 = _build_mem_content(0)
        gdb_v0 = _build_gdb_content(0)
        _place_in_panel(mem_v0, mem_panel)
        _place_in_panel(gdb_v0, gdb_panel)

        self.play(FadeIn(title, shift=0.2 * UP), FadeIn(badge_safe), run_time=0.5)
        self.play(FadeIn(mem_panel), FadeIn(gdb_panel), run_time=0.5)
        self.play(FadeIn(mem_v0), FadeIn(gdb_v0), run_time=0.6)
        self.next_slide()

        current_mem = mem_v0
        current_gdb = gdb_v0
        current_badge = badge_safe

        # Steps 1..5
        for step in range(1, 6):
            new_mem = _build_mem_content(step)
            new_gdb = _build_gdb_content(step)
            _place_in_panel(new_mem, mem_panel)
            _place_in_panel(new_gdb, gdb_panel)

            # Badge: switches to HIJACKED at step 3 (RIP overwritten) and stays
            hijacked_now = step >= 3
            target_badge = badge_danger if hijacked_now else badge_safe

            anims = [
                ReplacementTransform(current_mem, new_mem),
                ReplacementTransform(current_gdb, new_gdb),
            ]
            if target_badge is not current_badge:
                anims.append(ReplacementTransform(current_badge, target_badge))

            self.play(*anims, run_time=0.7)

            current_mem = new_mem
            current_gdb = new_gdb
            if target_badge is not current_badge:
                current_badge = target_badge

            # Final "ret to win" -> flash the success line
            if step == 5:
                # Find the win line inside current_gdb (last line)
                win_line = current_gdb[-1]
                self.play(Flash(win_line, color=SecurityPalette.SAFE,
                                flash_radius=0.8), run_time=0.5)

            self.next_slide() if step < 5 else self.wait(0.6)
