import argparse
from colorthief import ColorThief
import sys
import os

def extract_colors(image_path, num_colors=6):
    """
    Extracts a specified number of colors from an image using ColorThief.

    Args:
        image_path (str): The path to the image file.
        num_colors (int): The number of colors to extract in the palette.

    Returns:
        list: A list of RGB tuples representing the color palette,
              or None if the file is invalid or an error occurs.
    """
    if not os.path.exists(image_path):
        print(f"Error: Image file not found at '{image_path}'", file=sys.stderr)
        return None
    if not os.path.isfile(image_path):
         print(f"Error: Path '{image_path}' is not a file.", file=sys.stderr)
         return None

    try:
        color_thief = ColorThief(image_path)
        # Get the palette (will return num_colors or fewer if less are distinct)
        palette = color_thief.get_palette(color_count=num_colors)
        return palette
    except Exception as e:
        print(f"Error processing image '{image_path}': {e}", file=sys.stderr)
        return None

def rgb_to_hex(rgb):
    """Converts an RGB tuple to a hex color string."""
    return '#{:02x}{:02x}{:02x}'.format(rgb[0], rgb[1], rgb[2])

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Extract a color palette from an album art image.')
    parser.add_argument('image_file', type=str, help='Path to the album art image file.')
    parser.add_argument('-n', '--num_colors', type=int, default=4,
                        help='Number of colors to extract (default: 6)')
    parser.add_argument('--hex', action='store_true',
                        help='Output colors in hex format instead of RGB tuples.')

    args = parser.parse_args()

    palette = extract_colors(args.image_file, args.num_colors)

    if palette:
        print(f"Extracted {len(palette)} colors from '{args.image_file}':")
        if args.hex:
            hex_palette = [rgb_to_hex(color) for color in palette]
            for color in hex_palette:
                print(color)
        else:
            print(palette)
        sys.exit(0) # Exit successfully
    else:
        sys.exit(1) # Exit with error 