# cli.py
import argparse
from .file import Wallet, HashTx
from .main import help, versions, check_for_update
from colorama import Fore


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Tonviewer is a Python library to fetch wallet info, transactions, and transaction hash data.",
        add_help=False
    )

    parser.add_argument("-w", "--wallet",       type=str,            help="Wallet address")
    parser.add_argument("-i", "--info",         action="store_true", help="Get wallet info")
    parser.add_argument("-t", "--transactions", type=str,            help="Wallet address for transactions")
    parser.add_argument("-l", "--limit",        type=int,            help="Number of transactions to fetch")
    parser.add_argument("-H", "--hashtx",       type=str,            help="Transaction hash to query")
    parser.add_argument("-h", "--help",         action="store_true", help="Display help message")
    parser.add_argument("-v", "--version",      action="store_true", help="Display version info")
    parser.add_argument(
        "-a", "--action", type=str,
        help="Filter by action: 'Sent TON', 'Received TON', 'NFT Transfer', 'Transfer Token', 'Gas Relay'"
    )

    args, unknown = parser.parse_known_args()
    if unknown:
        for arg in unknown:
            print(
                f"[{Fore.RED}{arg}{Fore.WHITE}] No valid arguments provided. Use `{Fore.RED}-h{Fore.WHITE}` for help."
            )
        exit(1)

    return args


def run_cli():
    args = parse_args()

    try:
        if args.help:
            print(help())
            check_for_update("tonviewer")

        if args.version:
            print(versions())
            check_for_update("tonviewer")

        if args.hashtx:
            print(HashTx(hashtx=args.hashtx).get())
            check_for_update("tonviewer")

        if args.wallet and args.info:
            print(Wallet(wallet=args.wallet).info())
            check_for_update("tonviewer")

        if args.wallet and args.action:
            limit = args.limit if args.limit and args.limit > 0 else 1
            print(Wallet(wallet=args.wallet).action(action=args.action, limit=limit))
            check_for_update("tonviewer")


        wallet = args.transactions or args.wallet
        if wallet:
            limit = args.limit if args.limit and args.limit > 0 else 1
            print(Wallet(wallet=wallet).transactions(limit))
            check_for_update("tonviewer")

        print(
            f"[{Fore.RED}ERROR{Fore.WHITE}] No valid arguments provided. Use `{Fore.RED}-h{Fore.WHITE}` for help."
        )

    except Exception as e:
        print(f"[FATAL] Unexpected error: {e}")


def console():
    run_cli()


if __name__ == "__main__":
    console()