import hashlib

from recoil.pipeline._lib.breakdown_scenes import (
    scene_hash,
    script_content_hash,
    segment_scenes,
)


SCRIPT_FIXTURE = """# Episode 1 - Wake
**Word Count:** 420
hook: cold open
[[EPISODE 1]]
---

# [00:00 - 00:07] HOOK
INT. LOWER DECKS - CRYO BAY - NIGHT

Jade wakes under strobing amber light.   

JADE
Where am I?

# [00:07 - 00:14] ESCALATION
She palms condensation from the glass.

EXT. HULL WALKWAY - NIGHT

The ship turns above a black planet.

# [00:14 - 00:20] TURN
WREN
Do not look down.
"""


def test_segment_scenes_uses_sluglines_not_beat_headers():
    scenes = segment_scenes(SCRIPT_FIXTURE, episode=1)

    assert len(scenes) == 2
    assert [scene.scene_id for scene in scenes] == ["EP001_SC001", "EP001_SC002"]
    assert scenes[0].slugline == "INT. LOWER DECKS - CRYO BAY - NIGHT"
    assert scenes[1].slugline == "EXT. HULL WALKWAY - NIGHT"
    assert scenes[0].span_text.startswith("# [00:00 - 00:07] HOOK")
    assert "INT. LOWER DECKS - CRYO BAY - NIGHT" in scenes[0].span_text
    assert "# [00:07 - 00:14] ESCALATION" in scenes[0].span_text
    assert "# [00:07 - 00:14] ESCALATION" not in scenes[1].span_text
    assert "# [00:14 - 00:20] TURN" in scenes[1].span_text
    assert "Word Count" not in scenes[0].span_text
    assert "hook:" not in scenes[0].span_text


def test_beat_header_immediately_before_slugline_belongs_to_next_scene():
    script = """# Episode 1

# [00:00 - 00:05] HOOK
INT. FIRST ROOM - NIGHT

Jade waits.

# [00:05 - 00:10] CUTAWAY

EXT. WALKWAY - NIGHT

Wren runs.
"""

    first, second = segment_scenes(script, episode=1)

    assert "# [00:05 - 00:10] CUTAWAY" not in first.span_text
    assert second.span_text.startswith("# [00:05 - 00:10] CUTAWAY")


def test_segment_scene_ids_are_episode_scoped():
    scenes = segment_scenes(SCRIPT_FIXTURE, episode=12)

    assert [scene.scene_id for scene in scenes] == ["EP012_SC001", "EP012_SC002"]


def test_scene_hash_is_deterministic_and_content_sensitive():
    span = "INT. ROOM - NIGHT\nJade waits."

    assert scene_hash(span) == scene_hash(span)
    assert scene_hash(span) != scene_hash("INT. ROOM - NIGHT\nJade runs.")
    assert len(scene_hash(span)) == 64


def test_scene_hash_ignores_trailing_whitespace_per_line():
    clean = "INT. ROOM - NIGHT\nJade waits.\n\nWREN\nNow."
    edited = "INT. ROOM - NIGHT   \nJade waits.\t\n\nWREN   \nNow.  "

    assert scene_hash(clean) == scene_hash(edited)


def test_script_content_hash_uses_full_raw_script():
    assert script_content_hash(SCRIPT_FIXTURE) == hashlib.sha256(
        SCRIPT_FIXTURE.encode("utf-8")
    ).hexdigest()
    assert script_content_hash(SCRIPT_FIXTURE) != script_content_hash(
        SCRIPT_FIXTURE + "\n"
    )
