#!/usr/bin/env python3
"""Test the working Lark grammar against TCK queries."""

import json
from pathlib import Path
import time
import lark


def main():
    grammar_file = Path(__file__).parent / 'lark_grammars' / 'cypher_from_grammars_v4.lark'
    queries_file = Path(__file__).parent / 'tck-queries' / 'all_queries.json'

    # Load grammar
    print(f"Loading grammar from {grammar_file.name}...")
    grammar_text = grammar_file.read_text()
    parser = lark.Lark(grammar_text, parser='earley', ambiguity='explicit')
    print(f"Loaded {len(parser.rules)} rules")

    # Load queries
    with open(queries_file) as f:
        queries = json.load(f)
    print(f"Testing against {len(queries)} queries...\n")

    passed = 0
    failed = 0
    failures = []
    categories = {}

    start_time = time.time()

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

        category = q.get('category', 'unknown')

        try:
            tree = parser.parse(query_text)
            passed += 1
            categories[category] = categories.get(category, {'passed': 0, 'failed': 0})
            categories[category]['passed'] += 1
        except Exception as e:
            failed += 1
            categories[category] = categories.get(category, {'passed': 0, 'failed': 0})
            categories[category]['failed'] += 1
            if len(failures) < 30:
                failures.append({
                    'query': query_text[:150],
                    'category': category,
                    'error': str(e)[:150]
                })

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

    print("=" * 70)
    print("RESULTS")
    print("=" * 70)
    print(f"\nOverall: {passed}/{total} ({100*passed/total:.1f}%)")
    print(f"Time: {elapsed:.2f}s ({elapsed*1000/total:.1f}ms per query)")

    print(f"\nBy category (top 15 by failure count):")
    sorted_cats = sorted(categories.items(), key=lambda x: -x[1]['failed'])
    for cat, stats in sorted_cats[:15]:
        total_cat = stats['passed'] + stats['failed']
        pct = 100 * stats['passed'] / total_cat if total_cat > 0 else 0
        print(f"  {cat:30} {stats['passed']:4}/{total_cat:<4} ({pct:5.1f}%)")

    if failures:
        print(f"\n{'=' * 70}")
        print(f"SAMPLE FAILURES (first {min(15, len(failures))})")
        print("=" * 70)
        for i, f in enumerate(failures[:15]):
            print(f"\n{i+1}. [{f['category']}]")
            print(f"   Query: {f['query'][:100]}...")
            print(f"   Error: {f['error'][:100]}")


if __name__ == '__main__':
    main()
