"""Command-line interface for jmd."""
import sys
import argparse
from . import tokenize_stream, parse_stream

def detect_format_from_chunk(chunk):
    """Detect if input is JSON or JMD markdown from first chunk."""
    stripped = chunk.lstrip()
    if not stripped:
        return 'empty'
    if stripped.startswith('> '):
        return 'jmd'
    if stripped[0] in '{["0123456789tfn-':
        return 'json'
    return 'unknown'

def process_input(f, out):
    """Process input, detect format, convert or pass through."""
    # Read first chunk to detect format
    first_chunk = f.read(4096)
    if not first_chunk:
        return
    
    fmt = detect_format_from_chunk(first_chunk)
    
    if fmt == 'jmd':
        # Already markdown - pass through
        out.write(first_chunk)
        while True:
            chunk = f.read(65536)
            if not chunk:
                break
            out.write(chunk)
        return
    
    if fmt == 'empty':
        return
    
    if fmt == 'unknown':
        raise ValueError(f"Unknown format: {first_chunk[:50]!r}")
    
    # JSON input - stream through tokenizer
    def chunks_with_first():
        yield first_chunk
        while True:
            chunk = f.read(65536)
            if not chunk:
                yield ""  # EOF signal
                break
            yield chunk
    
    tokens = tokenize_stream(chunks_with_first())
    for line in parse_stream(tokens):
        out.write(line + "\n")
        out.flush()

def cli_entry():
    """Entry point for the jmd command."""
    parser = argparse.ArgumentParser(
        prog='jmd',
        description='Convert JSON to Markdown (streaming)',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog='''
Examples:
  cat data.json | jmd
  jmd data.json
  jmd records.jsonl | head -20
  
Supported formats:
  - JSONL (one JSON object per line)
  - Single-line JSON
  - Pretty-printed JSON
  - Concatenated JSON objects
  - Already-converted JMD markdown (passed through)
'''
    )
    parser.add_argument('file', nargs='?', help='Input file (default: stdin)')
    args = parser.parse_args()
    
    try:
        if args.file:
            with open(args.file, 'r') as f:
                process_input(f, sys.stdout)
        else:
            process_input(sys.stdin, sys.stdout)
    except BrokenPipeError:
        pass
    except KeyboardInterrupt:
        pass
    except ValueError as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)
    except FileNotFoundError as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)

if __name__ == "__main__":
    cli_entry()