"""
s10 - The exploit chain.

Mirrors the website's /chain visualization (web/static/js/pages/attack.js):
5 circular nodes connected by a dashed track, each with a stage number,
name, subtitle, and (for CVE stages) a CVE+CWE badge above the label.

Color coding:
  Stage 0 (Attacker), 1 (WhatsApp):   muted/slate
  Stage 2 (Authz Bypass, CVE-55177):  orange / WARN
  Stage 3 (ImageIO, CVE-43300):       orange / WARN
  Stage 4 (RCE):                      red / DANGER

A packet dot travels through the chain across next_slide() boundaries.
"""

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

from manim import (
    Text, Circle, Dot, DashedLine, Rectangle, VGroup, FadeIn, Create,
    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


def _node(stage_num: str, color, *, ring_inset=False) -> VGroup:
    """Circle with stage number inside. ring_inset=True for CVE/RCE highlight."""
    r = 0.55 if ring_inset else 0.50
    bg = Circle(radius=r, fill_color=SecurityPalette.BG_PANEL, fill_opacity=1.0,
                stroke_color=color, stroke_width=2.5)
    num = Text(stage_num, font=Fonts.SANS, font_size=18,
               color=color, weight="BOLD")
    num.move_to(bg.get_center())
    return VGroup(bg, num)


def _label(name: str, sub: str, color, badge: str | None = None) -> VGroup:
    """Below-node label: optional badge + name + subtitle."""
    parts = []
    if badge:
        badge_t = Text(badge, font=Fonts.SANS, font_size=10,
                       color=color, weight="BOLD")
        box = Rectangle(width=badge_t.width + 0.22, height=badge_t.height + 0.18,
                        fill_color=color, fill_opacity=0.18,
                        stroke_color=color, stroke_width=1.2)
        badge_t.move_to(box.get_center())
        parts.append(VGroup(box, badge_t))
    name_t = Text(name, font=Fonts.SANS, font_size=16,
                  color=color, weight="BOLD")
    parts.append(name_t)
    sub_t = Text(sub, font=Fonts.SANS, font_size=12,
                 color=SecurityPalette.FG_MUTED)
    parts.append(sub_t)
    return VGroup(*parts).arrange(DOWN, buff=0.12)


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

    def construct_content(self):
        self.skip_reversing = True

        title = slide_title(
            "Two CVEs.  Five stages.  Zero clicks.",
            font_size=Sizes.TITLE - 10, with_accent_rule=True,
        )
        title.move_to((0.0, 3.05, 0.0))

        gray = SecurityPalette.FG_MUTED
        warn = SecurityPalette.WARN
        red  = SecurityPalette.DANGER

        stages = [
            ("00", "Attacker",     "Craft DNG + sync message",       gray, None),
            ("01", "WhatsApp",     "Linked-device protocol",         gray, None),
            ("02", "Authz Bypass", "Sync accepted without auth",     warn, "CVE-2025-55177\nCWE-863"),
            ("03", "ImageIO",      "DNG parser OOB write",           warn, "CVE-2025-43300\nCWE-787"),
            ("04", "RCE",          "Code in parser process",         red,  None),
        ]

        n = len(stages)
        x_left   = Layout.LEFT_EDGE  + 1.5
        x_right  = Layout.RIGHT_EDGE - 1.5
        xs = [x_left + (x_right - x_left) * i / (n - 1) for i in range(n)]
        node_y = 0.85

        nodes = []
        labels = []
        for i, (num, name, sub, color, badge) in enumerate(stages):
            node = _node(num, color, ring_inset=(badge is not None or i == 4))
            node.move_to((xs[i], node_y, 0.0))
            nodes.append(node)

            label = _label(name, sub, color, badge=badge)
            label.next_to(node, DOWN, buff=0.45)
            labels.append(label)

        tracks = VGroup()
        for i in range(n - 1):
            seg = DashedLine(
                start=(xs[i] + 0.55, node_y, 0.0),
                end=(xs[i + 1] - 0.55, node_y, 0.0),
                color=SecurityPalette.RULE,
                stroke_width=2,
                dash_length=0.10,
            )
            tracks.add(seg)

        packet_glow = Circle(radius=0.18, color=SecurityPalette.INFO,
                             fill_color=SecurityPalette.INFO, fill_opacity=0.25,
                             stroke_width=0)
        packet_core = Circle(radius=0.11, color=SecurityPalette.INFO,
                             fill_color=SecurityPalette.INFO, fill_opacity=1.0,
                             stroke_width=0)
        packet = VGroup(packet_glow, packet_core)
        packet.move_to((xs[0], node_y, 0.0))

        # Brace + tag at bottom
        brace_y = Layout.BOTTOM_EDGE + 1.30
        brace_text = Text(
            "zero user interaction  -  arrives, parses, executes",
            font=Fonts.SERIF, font_size=22,
            color=SecurityPalette.DANGER,
        )
        brace_text.move_to((0.0, brace_y, 0.0))

        # Animate
        self.play(FadeIn(title, shift=0.2 * UP), run_time=0.5)
        self.play(*[FadeIn(n) for n in nodes], *[FadeIn(l) for l in labels],
                  run_time=0.7)
        self.play(*[Create(s) for s in tracks], run_time=0.5)
        self.next_slide()

        # Send packet through
        self.add(packet)
        for i in range(n - 1):
            self.play(packet.animate.move_to((xs[i + 1], node_y, 0.0)),
                      run_time=0.55)
        self.play(packet_core.animate.set_color(SecurityPalette.DANGER),
                  packet_glow.animate.set_color(SecurityPalette.DANGER),
                  run_time=0.4)
        self.next_slide()

        self.play(FadeIn(brace_text), run_time=0.5)
        self.wait(0.5)
        self.next_slide()
