#!/usr/bin/env python3
"""Verify version consistency across local files and live server."""

import json
import sys
import urllib.request

import tomllib


def main():
    pv = tomllib.load(open("pyproject.toml", "rb"))["project"]["version"]
    mv = json.load(open("manifest.json"))["version"]
    sv = json.load(open("server.json"))["version"]

    if not (pv == mv == sv):
        print(f"Version mismatch: pyproject.toml={pv}, manifest.json={mv}, server.json={sv}")
        print("Run: make mcp-version-sync")
        return 1

    print(f"Local versions match: v{pv}")

    try:
        req = urllib.request.Request(
            "https://mcp.obris.ai/.well-known/mcp/server-card.json",
            headers={"User-Agent": "obris-mcp/check-version"},
        )
        card = json.loads(urllib.request.urlopen(req, timeout=5).read())
        live = card["serverInfo"]["version"]
        if live == pv:
            print(f"Live server-card.json: v{live}")
        else:
            print(f"Live server-card.json: v{live} — MISMATCH, expected v{pv}. Deploy to update.")
            return 1
    except Exception as e:
        print(f"Could not check live version: {e}")

    return 0


if __name__ == "__main__":
    sys.exit(main())