"""Search result formatting utilities."""

import json

from rich.console import Console
from rich.markup import escape

from mykb.backends.base import SearchResult

console = Console()


def format_results_json(results: SearchResult) -> str:
    """Format search results as JSON."""
    output = []
    for hit in results.hits:
        doc = hit.document
        output.append(
            {
                'title': doc.get('title', ''),
                'source_path': doc.get('source_path', ''),
                'source_uri': doc.get('source_uri', ''),
                'collection': doc.get('collection', ''),
                'chunk_index': doc.get('chunk_index', 0),
                'score': hit.score,
                'content': doc.get('content', ''),
                'tags': doc.get('tags', []),
            }
        )
    return json.dumps(output, indent=2, ensure_ascii=False)


def format_results_rich(results: SearchResult, show_full: bool = False):
    """Format search results with rich terminal output."""
    if not results.hits:
        console.print('[yellow]No results found.[/yellow]')
        return

    console.print(f'\n[bold]{len(results.hits)} result(s)[/bold] (query time: {results.processing_time_ms}ms)\n')

    for i, hit in enumerate(results.hits, 1):
        doc = hit.document
        score = hit.score
        title = doc.get('title', 'Untitled')
        source = doc.get('source_path', '')
        collection = doc.get('collection', '')
        chunk_idx = doc.get('chunk_index', 0)
        tags = doc.get('tags', [])

        # Header line
        console.print(f'[bold cyan]{i}.[/bold cyan] [bold]{escape(title)}[/bold]  [dim]score={score:.4f}[/dim]')
        console.print(f'   [dim]{escape(collection)}:{escape(source)} (chunk {chunk_idx})[/dim]')

        if tags:
            tag_str = ' '.join(f'[magenta]#{t}[/magenta]' for t in tags[:5])
            console.print(f'   {tag_str}')

        # Content snippet
        if show_full:
            content = doc.get('content', '')
        else:
            # Use highlighted content if available, or truncate
            formatted = doc.get('_formatted', {})
            content = formatted.get('content', doc.get('content', ''))
            # Truncate to ~200 chars
            if len(content) > 200:
                content = content[:200] + '...'

        # Replace highlight markers with rich markup
        content = content.replace('<<', '[bold yellow]').replace('>>', '[/bold yellow]')
        console.print(f'   {content}')
        console.print()
