import json
from dataclasses import replace

from fastapi.testclient import TestClient

from sentence_api.main import create_app
from sentence_api.config import Settings
from sentence_api.repository import VideoRepository
from sentence_api.store import BoundaryStore


VIDEO_HASH = "a" * 64


def make_client(tmp_path):
    index_path = tmp_path / "boundaries.json"
    index_path.write_text(
        json.dumps({
            "videos": {
                VIDEO_HASH: {
                    "duration_ms": 9000,
                    "algorithm_version": "test-v1",
                    "sentences": [
                        {"index": 0, "start_ms": 0, "end_ms": 4000, "text": "One."},
                        {"index": 1, "start_ms": 4000, "end_ms": 9000, "text": "Two."},
                    ],
                }
            }
        }),
        encoding="utf-8",
    )
    settings = replace(
        Settings.from_env(),
        data_dir=tmp_path / "data",
        legacy_boundaries_file=index_path,
    )
    settings.ensure_directories()
    return TestClient(
        create_app(
            BoundaryStore(index_path),
            settings=settings,
            repository=VideoRepository(settings.database_path),
        )
    )


def test_lookup_returns_boundaries(tmp_path):
    client = make_client(tmp_path)

    response = client.get(f"/api/v1/videos/{VIDEO_HASH}/sentence-boundaries")

    assert response.status_code == 200
    assert response.json()["sentences"][1]["start_ms"] == 4000


def test_unknown_hash_returns_not_found(tmp_path):
    client = make_client(tmp_path)

    response = client.get(f"/api/v1/videos/{'b' * 64}/sentence-boundaries")

    assert response.status_code == 404
    assert response.json()["detail"]["code"] == "SENTENCE_BOUNDARIES_NOT_FOUND"


def test_invalid_hash_is_rejected(tmp_path):
    client = make_client(tmp_path)

    response = client.get("/api/v1/videos/not-a-sha256/sentence-boundaries")

    assert response.status_code == 422
