"""
Command-line interface for kousuan package
"""

import argparse
import sys

from kousuan.core import (
    add_numbers,
    subtract_numbers,
    multiply_numbers,
    divide_numbers,
    calculate_percentage,
    quick_addition,
    quick_multiplication,
    number_decomposition,
    mental_math_tricks,
    get_multiplication_table
)


def main():
    """Main entry point for the CLI"""
    parser = argparse.ArgumentParser(
        description="Kousuan Skill - Mental Arithmetic Calculation Tools",
        prog="kousuan"
    )

    subparsers = parser.add_subparsers(dest="command", help="Available commands")

    # Add command
    add_parser = subparsers.add_parser("add", help="Add two numbers")
    add_parser.add_argument("a", type=str, help="First number")
    add_parser.add_argument("b", type=str, help="Second number")

    # Subtract command
    sub_parser = subparsers.add_parser("subtract", help="Subtract two numbers")
    sub_parser.add_argument("a", type=str, help="First number")
    sub_parser.add_argument("b", type=str, help="Second number")

    # Multiply command
    mul_parser = subparsers.add_parser("multiply", help="Multiply two numbers")
    mul_parser.add_argument("a", type=str, help="First number")
    mul_parser.add_argument("b", type=str, help="Second number")

    # Divide command
    div_parser = subparsers.add_parser("divide", help="Divide two numbers")
    div_parser.add_argument("a", type=str, help="Dividend")
    div_parser.add_argument("b", type=str, help="Divisor")

    # Percentage command
    perc_parser = subparsers.add_parser("percentage", help="Calculate percentage")
    perc_parser.add_argument("value", type=str, help="Base value")
    perc_parser.add_argument("percentage", type=str, help="Percentage")

    # Quick addition command
    qadd_parser = subparsers.add_parser("qadd", help="Quick addition of multiple numbers")
    qadd_parser.add_argument("numbers", type=str, nargs="+", help="Numbers to add")

    # Quick multiplication command
    qmul_parser = subparsers.add_parser("qmul", help="Quick multiplication of multiple numbers")
    qmul_parser.add_argument("numbers", type=str, nargs="+", help="Numbers to multiply")

    # Decomposition command
    decomp_parser = subparsers.add_parser("decompose", help="Decompose number into prime factors")
    decomp_parser.add_argument("number", type=str, help="Number to decompose")

    # Tricks command
    tricks_parser = subparsers.add_parser("tricks", help="Show mental math tricks")

    # Table command
    table_parser = subparsers.add_parser("table", help="Generate multiplication table")
    table_parser.add_argument("number", type=int, help="Base number")
    table_parser.add_argument("--limit", type=int, default=10, help="Maximum multiplier (default: 10)")

    args = parser.parse_args()

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

    try:
        if args.command == "add":
            result = add_numbers(args.a, args.b)
            print(f"{args.a} + {args.b} = {result}")

        elif args.command == "subtract":
            result = subtract_numbers(args.a, args.b)
            print(f"{args.a} - {args.b} = {result}")

        elif args.command == "multiply":
            result = multiply_numbers(args.a, args.b)
            print(f"{args.a} × {args.b} = {result}")

        elif args.command == "divide":
            result = divide_numbers(args.a, args.b)
            print(f"{args.a} ÷ {args.b} = {result}")

        elif args.command == "percentage":
            result = calculate_percentage(args.value, args.percentage)
            print(f"{args.percentage}% of {args.value} = {result}")

        elif args.command == "qadd":
            result = quick_addition(args.numbers)
            numbers_str = " + ".join(map(str, args.numbers))
            print(f"{numbers_str} = {result}")

        elif args.command == "qmul":
            result = quick_multiplication(args.numbers)
            numbers_str = " × ".join(map(str, args.numbers))
            print(f"{numbers_str} = {result}")

        elif args.command == "decompose":
            result = number_decomposition(args.number)
            if result and isinstance(result, list) and len(result) > 0:
                factors = result[0].get("value", [])
                if factors:
                    factors_str = " × ".join(map(str, factors))
                    print(f"{args.number} = {factors_str}")
                else:
                    print(f"{args.number} cannot be decomposed (prime or < 2)")
            else:
                print(f"{args.number} cannot be decomposed (prime or < 2)")

        elif args.command == "tricks":
            tricks_result = mental_math_tricks()
            if tricks_result and len(tricks_result) > 0:
                tricks_data = tricks_result[0].get("value", [])
                print("Mental Math Tricks:")
                print("=" * 50)
                for trick in tricks_data:
                    print(f"\n{trick['name'].replace('_', ' ').title()}:")
                    print(f"  Explanation: {trick['explanation']}")
                    print(f"  Example: {trick['example']}")
            else:
                print("No mental math tricks available.")

        elif args.command == "table":
            result = get_multiplication_table(args.number, args.limit)
            if result and isinstance(result, list) and len(result) > 0:
                table_lines = result[0].get("value", [])
                print(f"Multiplication Table for {args.number}:")
                print("=" * 30)
                for line in table_lines:
                    print(line)
            else:
                print(f"Could not generate multiplication table for {args.number}")

    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()