#!/usr/bin/env python3

import yaml
import argparse

def hex_to_rgb(hex_color):
    """Converts a hex color string (e.g., 'RRGGBB') to an RGB tuple."""
    hex_color = hex_color.lstrip('#')
    
    if len(hex_color) != 6:
        raise ValueError(f"Invalid hex color format: {hex_color}. Expected 6 characters.")
        
    return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))

def print_color_block(hex_color, label):
    """Prints a colored block with a label using ANSI escape codes."""
    try:
        r, g, b = hex_to_rgb(hex_color)
    except ValueError as e:
        print(f"Error converting hex '{hex_color}' for '{label}': {e}")
        return

    luminosity = (r * 0.2126 + g * 0.7152 + b * 0.0722)
    
    if luminosity > 186:
        text_color_code = ";38;2;0;0;0" # black
    else:
        text_color_code = ";38;2;255;255;255" # white

    print(f"\x1b[48;2;{r};{g};{b}{text_color_code}m  {label.ljust(15)} \x1b[0m")

def main():
    parser = argparse.ArgumentParser(
        description="Display colors from a YAML color palette file in the terminal."
    )
    parser.add_argument(
        "yaml_file",
        metavar="YAML_FILE",
        type=str,
        help="Path to the YAML file containing the color palette."
    )
    
    args = parser.parse_args()
    
    yaml_file_path = args.yaml_file

    try:
        with open(yaml_file_path, 'r') as f:
            data = yaml.safe_load(f)
    except FileNotFoundError:
        print(f"Error: '{yaml_file_path}' not found.")
        return
    except yaml.YAMLError as e:
        print(f"Error parsing YAML file '{yaml_file_path}': {e}")
        return
    except Exception as e:
        print(f"An unexpected error occurred while reading '{yaml_file_path}': {e}")
        return

    system_name = data.get('system', 'N/A')
    theme_name = data.get('name', 'N/A')
    description = data.get('description', 'N/A')
    palette = data.get('palette', {})

    print(f"\x1b[1mSystem:\x1b[0m {system_name}")
    print(f"\x1b[1mTheme Name:\x1b[0m {theme_name}")
    print(f"\x1b[1mDescription:\x1b[0m {description}\n")

    print("\x1b[1mPalette Colors:\x1b[0m")
    
    sorted_palette_keys = sorted(palette.keys(), key=lambda x: (x.startswith('base'), x))
    
    for key in sorted_palette_keys:
        hex_color = palette.get(key)
        if hex_color:
            print_color_block(hex_color, key)
        else:
            print(f"Warning: Key '{key}' has no hexadecimal color value.")

if __name__ == "__main__":
    main()
