#!/usr/bin/env python3
"""Test grammar with filtered queries (excluding templates)."""

import json
import re
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...")
    parser = lark.Lark(grammar_file.read_text(), parser='earley')
    print(f"Loaded {len(parser.rules)} rules")

    # Load queries
    with open(queries_file) as f:
        queries = json.load(f)

    # Filter out template queries (contain <...> placeholders)
    template_pattern = re.compile(r'<[a-zA-Z_][a-zA-Z0-9_]*>')
    real_queries = [q for q in queries if not template_pattern.search(q.get('query', ''))]
    template_queries = len(queries) - len(real_queries)

    print(f"Total queries: {len(queries)}")
    print(f"Template queries (filtered): {template_queries}")
    print(f"Real queries to test: {len(real_queries)}\n")

    passed = 0
    failed = 0
    failures = []

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

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

    total = passed + failed
    print("=" * 70)
    print("RESULTS (excluding template queries)")
    print("=" * 70)
    print(f"\nReal Cypher queries: {passed}/{total} ({100*passed/total:.1f}%)")

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


if __name__ == '__main__':
    main()
