"""
Command-line interface for minson.

Usage:
    minson data.json
    minson data.json --output data.min.json
    minson data.json --stats
    echo '{"a": 1}' | minson -
"""

import argparse
import json
import sys

from .core import minify_file, token_savings, _from_string


def main():
    parser = argparse.ArgumentParser(
        prog="minson",
        description="Minify JSON to reduce LLM API token costs.",
    )
    parser.add_argument(
        "input",
        help="Path to a JSON file, or '-' to read from stdin.",
    )
    parser.add_argument(
        "-o", "--output",
        help="Write minified output to this file instead of stdout.",
        default=None,
    )
    parser.add_argument(
        "--stats",
        action="store_true",
        help="Print token savings statistics.",
    )

    args = parser.parse_args()

    if args.input == "-":
        raw = sys.stdin.read()
        result = _from_string(raw)
        if args.stats:
            stats = token_savings(raw)
            print_stats(stats)
        if args.output:
            with open(args.output, "w") as f:
                f.write(result)
        else:
            print(result)
    else:
        if args.stats:
            stats = token_savings(args.input)
            print_stats(stats)
        result = minify_file(args.input, args.output)
        if not args.output:
            print(result)


def print_stats(stats: dict):
    print(f"\n📊 Token Savings Estimate", file=sys.stderr)
    print(f"  Original:  {stats['original_chars']:,} chars (~{stats['original_chars']//4:,} tokens)", file=sys.stderr)
    print(f"  Minified:  {stats['minified_chars']:,} chars (~{stats['minified_chars']//4:,} tokens)", file=sys.stderr)
    print(f"  Saved:     {stats['chars_saved']:,} chars (~{stats['estimated_tokens_saved']:,} tokens, {stats['estimated_pct_saved']}%)\n", file=sys.stderr)


if __name__ == "__main__":
    main()