"""cdn-ai command-line interface.

Usage:
    cdn encode "Search the web for SpaceX news, top 5 results"
    cdn decode "!:srch 'SpaceX' /n:5 | sumz /fmt:bullets"
    cdn stats "Filter active users, group by region, sort descending"
    cdn validate "!:srch 'SpaceX' /n:5"
    cdn bench              # Run 90-scenario benchmark
    cdn tokenize "hello"   # Show BPE tokens
"""

import argparse
import json
import sys


def main():
    parser = argparse.ArgumentParser(
        prog="cdn",
        description="Condensa — hyper-efficient AI-to-AI communication language",
    )
    subparsers = parser.add_subparsers(dest="command", help="Available commands")

    # encode
    enc_parser = subparsers.add_parser("encode", help="Natural language → Condensa")
    enc_parser.add_argument("text", help="Natural language text to encode")

    # decode
    dec_parser = subparsers.add_parser("decode", help="Condensa → natural language")
    dec_parser.add_argument("text", help="Condensa message to decode")

    # stats
    stats_parser = subparsers.add_parser("stats", help="Encode with compression stats")
    stats_parser.add_argument("text", help="Natural language text to analyze")

    # validate
    val_parser = subparsers.add_parser("validate", help="Validate Condensa syntax")
    val_parser.add_argument("text", help="Condensa message to validate")

    # tokenize
    tok_parser = subparsers.add_parser("tokenize", help="Show BPE tokens")
    tok_parser.add_argument("text", help="Text to tokenize")

    # bench
    subparsers.add_parser("bench", help="Run 90-scenario benchmark")

    # version
    subparsers.add_parser("version", help="Show version")

    args = parser.parse_args()

    if not args.command:
        parser.print_help()
        return

    if args.command == "version":
        from cdn import __version__
        print(f"cdn-ai v{__version__} (Condensa v0.3)")
        return

    if args.command == "encode":
        from cdn import encode
        print(encode(args.text))

    elif args.command == "decode":
        from cdn import decode
        print(decode(args.text))

    elif args.command == "stats":
        from cdn import encode_with_stats
        stats = encode_with_stats(args.text)
        print(json.dumps(stats, indent=2))

    elif args.command == "validate":
        try:
            sys.path.insert(0, ".")
            from experiments.validation_suite import validate_condensa
            valid, issues = validate_condensa(args.text)
            if valid:
                print(f"VALID: {args.text}")
            else:
                print(f"INVALID: {args.text}")
                for issue in issues:
                    print(f"  - {issue}")
        except ImportError:
            # Fallback: basic validation
            from cdn import decode
            try:
                result = decode(args.text)
                print(f"VALID: {args.text}")
                print(f"  Decoded: {result}")
            except Exception as e:
                print(f"INVALID: {e}")

    elif args.command == "tokenize":
        from cdn import count_tokens, tokenize
        tokens = tokenize(args.text)
        print(f"Text: {args.text}")
        print(f"Tokens ({count_tokens(args.text)}): {tokens}")

    elif args.command == "bench":
        try:
            sys.path.insert(0, ".")
            from benchmarks.run_benchmarks import run_benchmarks
            run_benchmarks()
        except ImportError:
            print("Benchmarks require the full repository. Clone from:")
            print("  https://github.com/worachetdee/condensa")


if __name__ == "__main__":
    main()
