"""Contract tests: publishing metadata consistency across PyPI, plugin.json, and README.

Catches version drift, description mismatches, stale tool counts, and missing
platform mentions before they reach customers on PyPI, Glama, or Claude Code.
"""
from __future__ import annotations

import json
import re
from pathlib import Path

import pytest

_PROXY_DIR = Path(__file__).resolve().parent.parent
_PLUGIN_DIR = _PROXY_DIR.parent / ".claude-plugin"

_PYPROJECT = _PROXY_DIR / "pyproject.toml"
_INIT_PY = _PROXY_DIR / "src" / "rekko_mcp" / "__init__.py"
_PLUGIN_JSON = _PLUGIN_DIR / "plugin.json"
_README = _PROXY_DIR / "README.md"
_GLAMA = _PROXY_DIR / "glama.json"


def _pyproject_version() -> str:
    text = _PYPROJECT.read_text()
    match = re.search(r'^version\s*=\s*"([^"]+)"', text, re.MULTILINE)
    assert match, "No version in pyproject.toml"
    return match.group(1)


def _init_version() -> str:
    text = _INIT_PY.read_text()
    match = re.search(r'^__version__\s*=\s*"([^"]+)"', text, re.MULTILINE)
    assert match, "No __version__ in __init__.py"
    return match.group(1)


def _plugin_json() -> dict:
    return json.loads(_PLUGIN_JSON.read_text())


def _readme_text() -> str:
    return _README.read_text()


# ---------------------------------------------------------------------------
# Version consistency
# ---------------------------------------------------------------------------


def test_pyproject_and_init_versions_match():
    """pyproject.toml version must equal __init__.py __version__."""
    assert _pyproject_version() == _init_version(), (
        f"pyproject.toml={_pyproject_version()}, __init__.py={_init_version()}"
    )


def test_plugin_json_version_matches_pyproject():
    """plugin.json version must match pyproject.toml (PyPI) version."""
    plugin = _plugin_json()
    assert plugin["version"] == _pyproject_version(), (
        f"plugin.json={plugin['version']}, pyproject.toml={_pyproject_version()}. "
        f"Update plugin.json to match."
    )


# ---------------------------------------------------------------------------
# Tool count
# ---------------------------------------------------------------------------


@pytest.mark.asyncio
async def test_readme_tool_count_matches_registered():
    """The tool count in README.md matches the actual registered tool count."""
    from rekko_mcp.server import mcp

    tools = await mcp.list_tools()
    actual_count = len(tools)

    readme = _readme_text()
    match = re.search(r"(\d+)\s+MCP tools", readme)
    assert match, "README.md doesn't mention 'N MCP tools'"

    readme_count = int(match.group(1))
    assert readme_count == actual_count, (
        f"README says {readme_count} MCP tools but {actual_count} are registered. "
        f"Update the README."
    )


# ---------------------------------------------------------------------------
# Platform coverage
# ---------------------------------------------------------------------------

_REQUIRED_PLATFORMS = {"kalshi", "polymarket", "robinhood"}


def test_pyproject_description_mentions_all_platforms():
    """pyproject.toml description mentions all supported platforms."""
    text = _PYPROJECT.read_text().lower()
    for platform in _REQUIRED_PLATFORMS:
        assert platform in text, (
            f"pyproject.toml description missing platform: {platform}"
        )


def test_plugin_json_description_mentions_all_platforms():
    """plugin.json description mentions all supported platforms."""
    plugin = _plugin_json()
    desc = plugin.get("description", "").lower()
    for platform in _REQUIRED_PLATFORMS:
        assert platform in desc, (
            f"plugin.json description missing platform: {platform}. "
            f"Current: {plugin.get('description', '')}"
        )


def test_readme_mentions_all_platforms():
    """README.md mentions all supported platforms."""
    readme = _readme_text().lower()
    for platform in _REQUIRED_PLATFORMS:
        assert platform in readme, (
            f"README.md missing platform: {platform}"
        )


# ---------------------------------------------------------------------------
# Structural checks
# ---------------------------------------------------------------------------


def test_plugin_json_has_required_fields():
    """plugin.json has all fields needed for Claude Code plugin discovery."""
    plugin = _plugin_json()
    required = ["name", "version", "description"]
    for field in required:
        assert field in plugin, f"plugin.json missing required field: {field}"


def test_pyproject_has_entry_point():
    """pyproject.toml defines a console script entry point."""
    text = _PYPROJECT.read_text()
    assert "rekko-mcp" in text, "pyproject.toml missing rekko-mcp entry point"


def test_glama_json_valid():
    """glama.json parses and has required fields."""
    data = json.loads(_GLAMA.read_text())
    assert "$schema" in data, "glama.json missing $schema"
    assert "maintainers" in data, "glama.json missing maintainers"
    assert len(data["maintainers"]) > 0, "glama.json has empty maintainers list"
