"""Tests for manifest JSON Schema validation."""

import json
from pathlib import Path

import jsonschema
import pytest

from uitag.manifest import generate_manifest
from uitag.types import Detection, PipelineResult

SCHEMA_PATH = Path(__file__).parent.parent / "uitag" / "schema.json"


@pytest.fixture
def schema():
    return json.loads(SCHEMA_PATH.read_text())


def test_schema_file_exists():
    assert SCHEMA_PATH.exists(), f"Schema not found at {SCHEMA_PATH}"


def test_valid_manifest_passes_schema(schema):
    """A manifest generated by the pipeline should validate."""
    result = PipelineResult(
        detections=[
            Detection("Submit", 100, 200, 80, 30, 0.95, "vision_text", som_id=1),
            Detection("icon", 50, 50, 24, 24, 0.8, "florence2", som_id=2),
        ],
        image_width=1920,
        image_height=1080,
        timing_ms={"vision_ms": 189.0, "florence_total_ms": 650.0},
    )
    manifest = json.loads(generate_manifest(result))
    jsonschema.validate(manifest, schema)


def test_empty_manifest_passes_schema(schema):
    """An empty manifest should still validate."""
    result = PipelineResult(detections=[], image_width=800, image_height=600)
    manifest = json.loads(generate_manifest(result))
    jsonschema.validate(manifest, schema)


def test_invalid_manifest_fails_schema(schema):
    """A manifest with wrong types should fail validation."""
    bad_manifest = {
        "image_width": "not_a_number",
        "image_height": 1080,
        "element_count": 0,
        "elements": [],
    }
    with pytest.raises(jsonschema.ValidationError):
        jsonschema.validate(bad_manifest, schema)


def test_missing_required_field_fails_schema(schema):
    """A manifest missing required fields should fail."""
    incomplete = {"image_width": 1920}
    with pytest.raises(jsonschema.ValidationError):
        jsonschema.validate(incomplete, schema)
