#!/usr/bin/env python3
"""Test script for MCP tools against mock API.

Run with:
    .venv/bin/python scripts/test_mcp_tools.py
"""
import asyncio
import sys
sys.path.insert(0, "src")

from platform_2step_mcp.client import Platform2StepClient

API_URL = "http://localhost:8000"
MOCK_TOKEN = "mock-static-token"


async def test_list_categories():
    """Test listing categories."""
    print("\n--- Testing list_categories ---")
    client = Platform2StepClient(base_url=API_URL, token=MOCK_TOKEN)
    try:
        result = await client.list_categories(company_id=1234)
        print(f"Status: SUCCESS")
        print(f"Categories found: {len(result.get('data', []))}")
        for cat in result.get('data', []):
            print(f"  - {cat['id']}: {cat['name']}")
        return True
    except Exception as e:
        print(f"Status: FAILED - {e}")
        return False
    finally:
        await client.close()


async def test_get_category():
    """Test getting a single category."""
    print("\n--- Testing get_category ---")
    client = Platform2StepClient(base_url=API_URL, token=MOCK_TOKEN)
    try:
        result = await client.get_category(category_id=1)
        print(f"Status: SUCCESS")
        data = result.get('data', {})
        print(f"Category: {data.get('id')} - {data.get('name')}")
        return True
    except Exception as e:
        print(f"Status: FAILED - {e}")
        return False
    finally:
        await client.close()


async def test_list_services():
    """Test listing services."""
    print("\n--- Testing list_services ---")
    client = Platform2StepClient(base_url=API_URL, token=MOCK_TOKEN)
    try:
        result = await client.list_services(company_id=1234)
        print(f"Status: SUCCESS")
        print(f"Services found: {len(result.get('data', []))}")
        for svc in result.get('data', []):
            print(f"  - {svc['id']}: {svc['name']} (${svc.get('price', 'N/A')})")
        return True
    except Exception as e:
        print(f"Status: FAILED - {e}")
        return False
    finally:
        await client.close()


async def test_list_bookings():
    """Test listing bookings."""
    print("\n--- Testing list_bookings ---")
    client = Platform2StepClient(base_url=API_URL, token=MOCK_TOKEN)
    try:
        result = await client.list_bookings(
            company_id=1234,
            start_date="2024-12-01",
            end_date="2024-12-31",
        )
        print(f"Status: SUCCESS")
        print(f"Bookings found: {len(result.get('data', []))}")
        for booking in result.get('data', []):
            print(f"  - {booking['id']}: {booking.get('start')} ({booking.get('status')})")
        return True
    except Exception as e:
        print(f"Status: FAILED - {e}")
        return False
    finally:
        await client.close()


async def test_create_batch():
    """Test creating a batch operation."""
    print("\n--- Testing create_batch ---")
    client = Platform2StepClient(base_url=API_URL, token=MOCK_TOKEN)
    try:
        result = await client.create_batch(
            operations=[
                {"method": "POST", "path": "/api/v1/categories", "body": {"name": "Cat 1"}},
                {"method": "POST", "path": "/api/v1/categories", "body": {"name": "Cat 2"}},
            ],
            description="Batch create categories",
        )
        print(f"Status: SUCCESS")
        print(f"Batch ID: {result.batch_id}")
        print(f"Status: {result.status}")
        print(f"Operations: {result.operations_count}")
        return True
    except Exception as e:
        print(f"Status: FAILED - {e}")
        import traceback
        traceback.print_exc()
        return False
    finally:
        await client.close()


async def main():
    """Run all tests."""
    print("=" * 60)
    print("Testing MCP Tools against Mock API")
    print("=" * 60)
    print("\nMake sure mock API server is running on http://localhost:8000")
    print("Start with: .venv/bin/python scripts/mock_api.py\n")

    tests = [
        ("List Categories", test_list_categories),
        ("Get Category", test_get_category),
        ("List Services", test_list_services),
        ("List Bookings", test_list_bookings),
        ("Create Batch", test_create_batch),
    ]

    results = []
    for name, test in tests:
        try:
            passed = await test()
            results.append((name, passed))
        except Exception as e:
            print(f"Unexpected error in {name}: {e}")
            results.append((name, False))

    print("\n" + "=" * 60)
    print("TEST SUMMARY")
    print("=" * 60)
    for name, passed in results:
        status = "PASS" if passed else "FAIL"
        print(f"  {name}: {status}")

    all_passed = all(p for _, p in results)
    return 0 if all_passed else 1


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