import argparse
import sys
import shutil
from .core import convert_image, print_art, GRADIENT_DEFAULT, GRADIENT_DETAILED, GRADIENT_BLOCK

def main():
    # Auto-detect terminal width
    try:
        terminal_width = shutil.get_terminal_size().columns
        # Default to a reasonable size (100) or terminal width if smaller
        default_width = min(100, terminal_width - 2)
        default_width = max(20, default_width)
    except:
        default_width = 80

    parser = argparse.ArgumentParser(description="Convert images to ASCII art.")
    parser.add_argument("image_path", nargs="?", help="Path to the input image file.")
    parser.add_argument("--width", type=int, default=default_width, 
                        help=f"Width of the output ASCII art (default: {default_width}).")
    parser.add_argument("--contrast", type=float, default=1.5, help="Contrast enhancement factor (default: 1.5).")
    parser.add_argument("--brightness", type=float, default=1.2, help="Brightness enhancement factor (default: 1.2).")
    parser.add_argument("--sharpness", type=float, default=2.0, help="Sharpness enhancement factor (default: 2.0).")
    parser.add_argument("--gradient", type=str, default=None, help="Custom characters or 'block'/'detailed'.")
    parser.add_argument("--invert", action="store_true", help="Invert the gradient mapping.")
    parser.add_argument("--no-dither", action="store_true", help="Disable dithering (simple linear mapping).")
    
    parser.add_argument("--delay", type=float, default=0.04, help="Delay in seconds between lines (default: 0.04).")
    parser.add_argument("--typewriter", action="store_true", help="Enable character-by-character typewriter effect.")
    parser.add_argument("--color", action="store_true", help="Enable TrueColor (RGB) output.")

    args = parser.parse_args()
    from pathlib import Path

    if not args.image_path:
        default_image = Path(__file__).resolve().parent / "assets" / "original_kersh.jpg"
        args.image_path = str(default_image)

    gradient = args.gradient
    if gradient == "block":
        gradient = GRADIENT_BLOCK
    elif gradient == "detailed":
        gradient = GRADIENT_DETAILED
    elif gradient is None:
        gradient = GRADIENT_DEFAULT

    try:
        ascii_art = convert_image(
            image_path=args.image_path,
            width=args.width,
            contrast=args.contrast,
            brightness=args.brightness,
            sharpness=args.sharpness,
            gradient=gradient,
            inversed=args.invert,
            dither=not args.no_dither,
            color=True
        )
        
        # Use the shared print_art function
        print_art(ascii_art, delay=args.delay, typewriter=args.typewriter)
                
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)

if __name__ == "__main__":
    main()
