"""Command-line interface for yakit."""

import argparse
import sys
from pathlib import Path


def main():
    """Main CLI entry point."""
    parser = argparse.ArgumentParser(
        prog="yakit",
        description="Yakut language text normalizer",
    )
    
    subparsers = parser.add_subparsers(dest="command", help="Available commands")
    
    # normalize command
    normalize_parser = subparsers.add_parser(
        "normalize",
        help="Normalize Yakut text",
    )
    normalize_parser.add_argument(
        "text",
        nargs="?",
        help="Text to normalize (or use --input for file)",
    )
    normalize_parser.add_argument(
        "-i", "--input",
        type=Path,
        help="Input file path",
    )
    normalize_parser.add_argument(
        "-o", "--output",
        type=Path,
        help="Output file path (default: stdout)",
    )
    normalize_parser.add_argument(
        "--model",
        type=Path,
        help="Path to Word2Vec model (default: auto-download)",
    )
    normalize_parser.add_argument(
        "--training-data",
        type=Path,
        help="Path to training data (default: auto-download)",
    )
    
    # download command
    download_parser = subparsers.add_parser(
        "download",
        help="Download models and data",
    )
    download_parser.add_argument(
        "--force",
        action="store_true",
        help="Re-download even if files exist",
    )
    download_parser.add_argument(
        "--model-only",
        action="store_true",
        help="Download only the Word2Vec model",
    )
    download_parser.add_argument(
        "--data-only",
        action="store_true",
        help="Download only the training data",
    )
    
    # info command
    subparsers.add_parser(
        "info",
        help="Show cache and model information",
    )
    
    args = parser.parse_args()
    
    if args.command == "normalize":
        cmd_normalize(args)
    elif args.command == "download":
        cmd_download(args)
    elif args.command == "info":
        cmd_info(args)
    else:
        parser.print_help()
        sys.exit(1)


def cmd_normalize(args):
    """Handle normalize command."""
    from yakit.normalizers import Word2VecNormalizer
    
    # Get input text
    if args.input:
        if not args.input.exists():
            print(f"Error: Input file not found: {args.input}", file=sys.stderr)
            sys.exit(1)
        text = args.input.read_text(encoding="utf-8")
    elif args.text:
        text = args.text
    else:
        # Read from stdin
        print("Enter text to normalize (Ctrl+D to finish):", file=sys.stderr)
        text = sys.stdin.read()
    
    # Create normalizer
    try:
        normalizer = Word2VecNormalizer(
            word2vec_path=args.model,
            training_data_path=args.training_data,
        )
    except Exception as e:
        print(f"Error initializing normalizer: {e}", file=sys.stderr)
        sys.exit(1)
    
    # Normalize text
    normalized = normalizer.normalize(text)
    
    # Output
    if args.output:
        args.output.write_text(normalized, encoding="utf-8")
        print(f"Normalized text written to {args.output}")
    else:
        print(normalized)


def cmd_download(args):
    """Handle download command."""
    from yakit.utils.download import download_model, download_training_data
    
    download_all = not args.model_only and not args.data_only
    
    if download_all or not args.data_only:
        print("Downloading Word2Vec model...")
        try:
            path = download_model(force=args.force)
            print(f"Model downloaded to: {path}")
        except Exception as e:
            print(f"Error downloading model: {e}", file=sys.stderr)
            if not download_all:
                sys.exit(1)
    
    if download_all or not args.model_only:
        print("Downloading training data...")
        try:
            path = download_training_data(force=args.force)
            print(f"Training data downloaded to: {path}")
        except Exception as e:
            print(f"Error downloading training data: {e}", file=sys.stderr)
            if not download_all:
                sys.exit(1)
    
    print("Done!")


def cmd_info(args):
    """Handle info command."""
    from yakit import __version__
    from yakit.utils.download import get_cache_dir, get_model_path
    
    print(f"Yakit version: {__version__}")
    print(f"Cache directory: {get_cache_dir()}")
    print()
    
    model_path = get_model_path("yak_word2vec.bin")
    data_path = get_model_path("train_pairs.txt")
    
    print("Downloaded files:")
    if model_path.exists():
        size_mb = model_path.stat().st_size / (1024 * 1024)
        print(f"  - Word2Vec model: {model_path} ({size_mb:.1f} MB)")
    else:
        print(f"  - Word2Vec model: not downloaded")
    
    if data_path.exists():
        size_kb = data_path.stat().st_size / 1024
        lines = sum(1 for _ in open(data_path, encoding="utf-8"))
        print(f"  - Training data: {data_path} ({size_kb:.1f} KB, {lines} pairs)")
    else:
        print(f"  - Training data: not downloaded")


if __name__ == "__main__":
    main()
