#!/usr/bin/env python3
"""End-to-end test: invoke every tool handler against the live dev API."""

import os
import sys

os.environ.setdefault("NETSCOPE_URL", "https://127.0.0.1:8443")
os.environ.setdefault("NETSCOPE_USER", "admin")
os.environ.setdefault("NETSCOPE_PASS", "GwEFrLRk2Xg5YMh")
os.environ.setdefault("NETSCOPE_VERIFY_TLS", "false")

from netscope_mcp.server import _dispatch, TOOLS  # noqa: E402
from netscope_mcp.validators import ValidationError  # noqa: E402

passed = 0
failed = 0

def test(name, args):
    global passed, failed
    try:
        result = _dispatch(name, args)
        if not result or len(result) < 5:
            print(f"WARN {name}: empty or very short result ({len(result)} chars)")
            failed += 1
        else:
            first_line = result.split("\n")[0][:80]
            print(f"OK   {name}: {first_line}")
            passed += 1
    except Exception as e:
        print(f"ERR  {name}: {e.__class__.__name__}: {e}")
        failed += 1

print(f"netscope-mcp: {len(TOOLS)} tools loaded\n")

test("search_services", {"query": "port:443", "limit": 3})
test("search_hosts", {"query": "port:22", "limit": 3})
test("get_facets", {"query": ""})
test("get_facets", {"query": "port:443"})
test("get_dashboard", {})
test("get_findings", {"limit": 5})
test("get_findings", {"query": "port:443", "limit": 3})
test("get_webapps", {"limit": 5})
test("get_ports", {"limit": 5})
test("explore", {"category": "countries"})
test("explore", {"category": "findings"})
test("explore", {"category": "products"})
test("get_drones", {})
test("search_templates", {"query": "CVE-2020", "limit": 3})
test("search_templates", {"severity": "critical", "limit": 3})
test("get_gallery", {"limit": 3})

# Detail endpoints: find a real service_id and IP first
from netscope_mcp import api_client  # noqa: E402
try:
    data = api_client.search_services({"q": "port:80", "limit": 1})
    results = data.get("results", [])
    if results:
        sid = results[0].get("service_id")
        ip = results[0].get("ip")
        test("get_service", {"service_id": sid})
        test("get_host", {"ip": ip})
    else:
        print("SKIP get_service/get_host: no services found")
except Exception as e:
    print(f"ERR  fetching test data: {e}")

# Validation tests
try:
    _dispatch("explore", {"category": "invalid"})
    print("ERR  validation: should have raised ValidationError")
    failed += 1
except ValidationError:
    print("OK   validation: invalid category rejected")
    passed += 1

print(f"\n{'='*40}")
print(f"Results: {passed} passed, {failed} failed")
sys.exit(1 if failed else 0)
