"""Run with the server checkout's .venv/bin/python; writes disposable test copies.
Usage: python verify.py --server-dir /path/to/inkscape-mcp --fixture before.svg
"""
import argparse
import asyncio
import json
import os
from pathlib import Path
import shutil
import tempfile
import xml.etree.ElementTree as ET
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def verify(server, fixture):
    with tempfile.TemporaryDirectory(prefix="inkscape-mcp-test-") as folder:
        work = Path(folder)
        original = fixture.read_bytes()
        (work / "before.svg").write_bytes(original)
        params = StdioServerParameters(command=shutil.which("uv") or "uv", args=[
            "--directory", str(server), "run", "--no-sync", "inkscape-mcp", "--mode", "stdio"
        ], env=dict(os.environ))
        results = {}
        async with stdio_client(params) as (reader, writer):
            async with ClientSession(reader, writer) as session:
                await session.initialize()
                tools = await session.list_tools()
                results["tool_count"] = len(tools.tools)
                results["tools"] = [t.name for t in tools.tools]
                async def call(label, name, args):
                    response = await session.call_tool(name, args)
                    data = response.structuredContent or json.loads(response.content[0].text)
                    results[label] = data
                    return data
                await call("status", "inkscape_system", {"operation": "status"})
                recolor = await call("recolor", "inkscape_vector", {
                    "operation": "bulk_restyle", "input_path": str(work / "before.svg"),
                    "output_path": str(work / "recolored.svg"), "selector": "#badge",
                    "params": {"fill": "#16a34a"}
                })
                assert recolor["success"], recolor
                text = await call("text", "inkscape_vector", {
                    "operation": "text_set_content", "input_path": str(work / "recolored.svg"),
                    "output_path": str(work / "after.svg"), "object_id": "title", "text": "Ready"
                })
                assert text["success"], text
                root = ET.parse(work / "after.svg").getroot()
                badge, title = root.find(".//*[@id='badge']"), root.find(".//*[@id='title']")
                assert badge is not None and badge.tag.endswith("circle") and badge.get("fill") == "#16a34a"
                assert title is not None and title.tag.endswith("text") and title.text == "Ready"
                assert (work / "before.svg").read_bytes() == original
                results["checks"] = {"editable_circle": True, "editable_text": True, "original_unchanged": True}
                await call("export", "inkscape_file", {
                    "operation": "convert", "input_path": str(work / "after.svg"),
                    "output_path": str(work / "after.png"), "format": "png"
                })
                output = Path.cwd() / "inkscape-test-output"
                output.mkdir(exist_ok=True)
                for name in ["before.svg", "after.svg", "after.png"]:
                    if (work / name).exists():
                        shutil.copyfile(work / name, output / name)
                summary = json.dumps(results, indent=2).replace(str(work), "WORKSPACE")
                (output / "results.json").write_text(summary)
                print(summary)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--server-dir", required=True, type=Path)
    parser.add_argument("--fixture", required=True, type=Path)
    args = parser.parse_args()
    asyncio.run(verify(args.server_dir.resolve(), args.fixture.resolve()))
