# SPDX-License-Identifier: AGPL-3.0-only
# Copyright (c) 2026 sol pbc

import json
import shutil
from pathlib import Path

import pytest

from solstone.apps.transcripts.tests._media_helpers import build_moov_at_tail_m4a
from solstone.convey import create_app

DAY = "20990104"
STREAM = "transcript-fixture"
SEGMENT = "122500_300"
MEDIA_FILE = "display_1_screen.mp4"
AUDIO_FILE = "raw.m4a"
IMAGE_FILE = "mentra-photo-1.jpg"
FIXTURE_MEDIA = Path(__file__).parent / "fixtures" / "tiny-h264.mp4"
SERVE_URL = f"/app/transcripts/api/serve_file/{DAY}/{STREAM}/{SEGMENT}/{MEDIA_FILE}"
AUDIO_SERVE_URL = (
    f"/app/transcripts/api/serve_file/{DAY}/{STREAM}/{SEGMENT}/{AUDIO_FILE}"
)
IMAGE_SERVE_URL = (
    f"/app/transcripts/api/serve_file/{DAY}/{STREAM}/{SEGMENT}/{IMAGE_FILE}"
)


@pytest.fixture
def client(tmp_path, monkeypatch):
    journal = tmp_path / "journal"
    config_dir = journal / "config"
    config_dir.mkdir(parents=True)
    (config_dir / "journal.json").write_text(
        json.dumps(
            {
                "setup": {"completed_at": 1700000000000},
            },
            indent=2,
        ),
        encoding="utf-8",
    )
    segment_dir = journal / "chronicle" / DAY / STREAM / SEGMENT
    segment_dir.mkdir(parents=True)
    shutil.copyfile(FIXTURE_MEDIA, segment_dir / MEDIA_FILE)
    if shutil.which("ffmpeg") is None:
        pytest.skip("ffmpeg not installed")
    build_moov_at_tail_m4a(segment_dir / AUDIO_FILE, 3.0)
    (segment_dir / IMAGE_FILE).write_bytes(b"\xff\xd8\xff\xe0jpeg")
    monkeypatch.setenv("SOLSTONE_JOURNAL", str(journal))
    app = create_app(str(journal))
    return app.test_client()


def test_serve_file_path_traversal_returns_non_200(client):
    response = client.get(
        "/app/transcripts/api/serve_file/20240101/../../../etc/passwd"
    )

    assert response.status_code == 403
    assert response.get_json()["reason_code"] == "invalid_path"


def test_serve_file_malformed_day_returns_404(client):
    response = client.get("/app/transcripts/api/serve_file/notadate/foo")

    assert response.status_code == 404


def test_serve_file_returns_video_mp4_with_range_support(client):
    response = client.get(SERVE_URL)

    assert response.status_code == 200
    assert response.headers["Content-Type"].startswith("video/mp4")
    assert response.data[4:8] == b"ftyp"

    range_response = client.get(SERVE_URL, headers={"Range": "bytes=0-127"})

    assert range_response.status_code == 206
    assert range_response.headers["Accept-Ranges"] == "bytes"
    assert range_response.headers["Content-Range"].startswith("bytes 0-127/")
    assert len(range_response.data) == 128


def test_serve_file_returns_audio_m4a_with_range_support(client):
    response = client.get(AUDIO_SERVE_URL)

    assert response.status_code == 200
    assert response.headers["Content-Type"].startswith("audio/mp4")

    range_response = client.get(AUDIO_SERVE_URL, headers={"Range": "bytes=0-127"})

    assert range_response.status_code == 206
    assert range_response.headers["Accept-Ranges"] == "bytes"
    assert range_response.headers["Content-Range"].startswith("bytes 0-127/")
    assert len(range_response.data) == 128


def test_serve_file_returns_image_jpeg(client):
    response = client.get(IMAGE_SERVE_URL)

    assert response.status_code == 200
    assert response.headers["Content-Type"].startswith("image/jpeg")
    assert response.data.startswith(b"\xff\xd8")
