"""
Command-line interface for PCompressLR.
"""

import sys
import os
from .api_client import PcompresslrAPIClient, APIKeyError, RateLimitError, APIRequestError


def main():
    """Main CLI entry point."""
    if len(sys.argv) < 2:
        print("Usage: pcompresslr <prompt>")
        print("\nExample:")
        print('  pcompresslr "hello world hello world hello world"')
        print("\nNote: Requires PCOMPRESLR_API_KEY environment variable")
        return
    
    prompt = " ".join(sys.argv[1:])
    
    # Get API key from environment
    api_key = os.getenv("PCOMPRESLR_API_KEY")
    if not api_key:
        print("Error: PCOMPRESLR_API_KEY environment variable is required.")
        print("\nTo get an API key, visit https://compress.lightreach.io")
        print("Then set it with: export PCOMPRESLR_API_KEY=your-key-here")
        sys.exit(1)
    
    # Initialize API client
    try:
        client = PcompresslrAPIClient(api_key=api_key)
    except APIKeyError as e:
        print(f"Error: {e}")
        sys.exit(1)
    
    print(f"Original prompt: {prompt!r}")
    print(f"Length: {len(prompt)} characters\n")
    print("=" * 80)
    
    print("\nGREEDY COMPRESSOR")
    print("-" * 80)
    try:
        result = client.compress(
            prompt=prompt,
            model="gpt-4",
            algorithm="greedy"
        )
        
        compressed = result["compressed"]
        dictionary = result["dictionary"]
        ratio = result["compression_ratio"]
        llm_format = result["llm_format"]
        
        # Verify decompression
        decompress_result = client.decompress(llm_format)
        decompressed = decompress_result["decompressed"]
        
        print(f"Compressed: {compressed!r}")
        print(f"Dictionary: {dictionary}")
        print(f"Compression ratio: {ratio:.2%}")
        print(f"LLM-ready format length: {len(llm_format)} chars")
        print(f"Processing time: {result['processing_time_ms']:.2f}ms")
        if decompressed == prompt:
            print("Decompression verified")
        else:
            print("Decompression failed")
    except RateLimitError as e:
        print(f"Rate limit exceeded: {e}")
    except APIRequestError as e:
        print(f"API error: {e}")


if __name__ == "__main__":
    main()
