#!/usr/bin/env python3
"""Test antlr4-cypher package against TCK queries."""

import json
from pathlib import Path
import time


def test_antlr4_cypher():
    """Test antlr4-cypher parser against TCK queries."""
    try:
        from antlr4 import CommonTokenStream, InputStream
        from antlr4_cypher import CypherLexer, CypherParser
    except ImportError as e:
        print(f"Import error: {e}")
        return

    # Load queries
    queries_file = Path(__file__).parent / 'tck-queries' / 'all_queries.json'
    with open(queries_file) as f:
        queries = json.load(f)

    print(f"Testing antlr4-cypher against {len(queries)} queries...")

    passed = 0
    failed = 0
    failures = []

    start_time = time.time()

    for q in queries:
        query_text = q.get('query', '')
        if not query_text.strip():
            continue

        try:
            input_stream = InputStream(query_text)
            lexer = CypherLexer(input_stream)
            token_stream = CommonTokenStream(lexer)
            parser = CypherParser(token_stream)

            # Parse - script is the start rule
            tree = parser.script()

            # Check for syntax errors
            if parser.getNumberOfSyntaxErrors() > 0:
                failed += 1
                if len(failures) < 20:
                    failures.append({
                        'query': query_text[:100],
                        'category': q.get('category', 'unknown'),
                        'error': f"{parser.getNumberOfSyntaxErrors()} syntax errors"
                    })
            else:
                passed += 1

        except Exception as e:
            failed += 1
            if len(failures) < 20:
                failures.append({
                    'query': query_text[:100],
                    'category': q.get('category', 'unknown'),
                    'error': str(e)[:100]
                })

    elapsed = time.time() - start_time
    total = passed + failed

    print(f"\nResults:")
    print(f"  Passed: {passed}/{total} ({100*passed/total:.1f}%)")
    print(f"  Failed: {failed}/{total}")
    print(f"  Time: {elapsed:.2f}s ({elapsed*1000/total:.1f}ms per query)")

    if failures:
        print(f"\nFirst {len(failures)} failures:")
        for i, f in enumerate(failures[:10]):
            print(f"\n{i+1}. [{f['category']}]")
            print(f"   Query: {f['query']}...")
            print(f"   Error: {f['error']}")

    return passed, failed


if __name__ == '__main__':
    test_antlr4_cypher()
