import argparse
import sys
import json
from njft.converter import get_token_proxy_metrics

def display_metrics(analysis_results):
    """Prints the conversion metrics to the console."""
    print("="*80)
    print("             JSON to TOON Conversion and Metric Analysis")
    print("="*80)
    print("\n--- Input JSON (Character Count: {}) ---".format(analysis_results['metrics']['input']['char_count']))
    print(analysis_results['input_json'])
    print("\n--- Output TOON (Character Count: {}) ---".format(analysis_results['metrics']['output']['char_count']))
    print(analysis_results['output_toon'])
    print("\n" + "="*80)
    print("                 Token Proxy Metrics Summary")
    print("="*80)
    print("Metric Type          | Input (JSON) | Output (TOON)")
    print("---------------------|--------------|--------------")
    print("Total Characters     | {:<12} | {:<12}".format(
        analysis_results['metrics']['input']['char_count'],
        analysis_results['metrics']['output']['char_count']
    ))
    print("Estimated Words      | {:<12} | {:<12}".format(
        analysis_results['metrics']['input']['word_count'],
        analysis_results['metrics']['output']['word_count']
    ))
    print("---------------------|--------------|--------------")
    char_reduction_percent = analysis_results['metrics']['reduction']['char_percent']
    print(f"\nCOMPRESSION EFFICIENCY (Character-based): {char_reduction_percent:.2f}% Reduction")
    print("-" * 80)
    print("\nNOTE: Character and Word Counts are proxies for LLM Token Count.")

def main():
    """
    Main function to handle command-line arguments for JSON to TOON conversion.
    """
    parser = argparse.ArgumentParser(
        description="Convert a nested JSON file into a flattened TOON format.",
        formatter_class=argparse.RawTextHelpFormatter
    )
    parser.add_argument(
        "input_file",
        help="Path to the input JSON file. Use '-' to read from stdin."
    )
    parser.add_argument(
        "-o", "--output",
        dest="output_file",
        help="Path to the output TOON file. If not provided, prints to stdout."
    )
    parser.add_argument(
        "-m", "--metrics",
        action="store_true",
        help="Display conversion metrics and comparison instead of just the output."
    )
    args = parser.parse_args()

    try:
        if args.input_file == '-':
            input_json_str = sys.stdin.read()
        else:
            with open(args.input_file, 'r', encoding='utf-8') as f:
                input_json_str = f.read()

        analysis_results = get_token_proxy_metrics(input_json_str)
        toon_output = analysis_results["output_toon"]

        if args.metrics:
            display_metrics(analysis_results)
        else:
            if args.output_file:
                with open(args.output_file, 'w', encoding='utf-8') as f:
                    f.write(toon_output)
                print(f"Successfully converted '{args.input_file}' to '{args.output_file}'.")
            else:
                sys.stdout.write(toon_output)

    except FileNotFoundError:
        print(f"Error: Input file not found at '{args.input_file}'", file=sys.stderr)
        sys.exit(1)
    except (json.JSONDecodeError, ValueError) as e:
        print(f"Error: Invalid JSON in '{args.input_file}'. Please check the format.\n{e}", file=sys.stderr)
        sys.exit(1)
    except Exception as e:
        print(f"An unexpected error occurred: {e}", file=sys.stderr)
        sys.exit(1)