#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
TKE UI/UX Pro Max Search - BM25 search engine for TKE UI standards

Enhanced with:
- Query expansion (synonyms)
- Field-weighted BM25 ranking
- Index caching for performance

Usage: python search.py "<query>" [--domain <domain>] [--max-results 3] [options]

Domains: component, form, table, layout, color, typography, practice, pattern, icon, responsive
"""

import argparse
from core import CSV_CONFIG, AVAILABLE_DOMAINS, MAX_RESULTS, search


def format_output(result, explain=False):
    """Format results for Claude consumption (token-optimized)"""
    if "error" in result:
        return f"Error: {result['error']}"

    output = []
    output.append(f"## TKE UI/UX Pro Max Search Results")
    domain_info = result['domain']
    if result.get('searched_domains') and len(result['searched_domains']) > 1:
        domain_info += f" (searched: {', '.join(result['searched_domains'])})"
    if result.get('confidence') is not None:
        domain_info += f" [confidence: {result['confidence']:.2f}]"
    output.append(f"**Domain:** {domain_info} | **Query:** {result['query']}")
    output.append(f"**Source:** {result['file']} | **Found:** {result['count']} results\n")

    explanations = result.get('explanations', [])
    
    for i, row in enumerate(result['results'], 1):
        output.append(f"### Result {i}")
        
        # Add explanation if available
        if explain and i <= len(explanations) and explanations[i-1]:
            exp = explanations[i-1]
            if exp.get('score'):
                output.append(f"**Match Score:** {exp['score']}")
            if exp.get('matched_keywords'):
                output.append(f"**Matched Keywords:** {', '.join(exp['matched_keywords'][:5])}")
            if exp.get('matched_fields'):
                field_info = []
                for field, keywords in list(exp['matched_fields'].items())[:3]:
                    field_info.append(f"{field}({', '.join(keywords[:2])})")
                if field_info:
                    output.append(f"**Matched Fields:** {', '.join(field_info)}")
            if exp.get('synonym_expansions') and i == 1:  # Only show for first result
                syn_info = []
                for orig, syns in list(exp['synonym_expansions'].items())[:3]:
                    syn_info.append(f"{orig}→{', '.join(syns[:2])}")
                if syn_info:
                    output.append(f"**Synonym Expansions:** {', '.join(syn_info)}")
            output.append("")
        
        for key, value in row.items():
            value_str = str(value)
            if len(value_str) > 300:
                value_str = value_str[:300] + "..."
            output.append(f"- **{key}:** {value_str}")
        output.append("")

    return "\n".join(output)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="TKE UI/UX Pro Max Search (Enhanced BM25 with query expansion and field weighting)",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  python search.py "button primary"
  python search.py "btn" --domain component
  python search.py "表单输入框" --max-results 5
  python search.py "hover cursor" --domain component --json

Performance Options:
  --no-weights    : Disable field weighting (use standard BM25)
  --no-cache      : Disable index caching (rebuild index each time)
  --no-expansion  : Disable query expansion (no synonym matching)
        """
    )
    parser.add_argument("query", help="Search query")
    parser.add_argument("--domain", "-d", choices=AVAILABLE_DOMAINS, help="Search domain")
    parser.add_argument("--max-results", "-n", type=int, default=MAX_RESULTS, help="Max results (default: 3)")
    parser.add_argument("--json", action="store_true", help="Output as JSON")
    
    # Performance/debugging options
    parser.add_argument("--no-weights", action="store_true", help="Disable field weighting")
    parser.add_argument("--no-cache", action="store_true", help="Disable index caching")
    parser.add_argument("--no-expansion", action="store_true", help="Disable query expansion")
    parser.add_argument("--multi-domain", action="store_true", help="Search multiple domains when confidence is low")
    parser.add_argument("--no-fallback", action="store_true", help="Disable automatic fallback to other domains")
    parser.add_argument("--min-results", type=int, default=1, help="Minimum results required before fallback (default: 1)")
    parser.add_argument("--explain", action="store_true", help="Show explanation of search results (matched keywords, fields, synonyms)")

    args = parser.parse_args()

    # Prepare search options
    use_weights = not args.no_weights
    use_cache = not args.no_cache
    expand_synonyms = not args.no_expansion
    auto_fallback = not args.no_fallback
    
    result = search(
        args.query, 
        args.domain,
        args.max_results,
        use_weights=use_weights,
        use_cache=use_cache,
        expand_synonyms=expand_synonyms,
        multi_domain=args.multi_domain,
        auto_fallback=auto_fallback,
        min_results=args.min_results,
        explain=args.explain
    )

    if args.json:
        import json
        print(json.dumps(result, indent=2, ensure_ascii=False))
    else:
        print(format_output(result, explain=args.explain))
