# -*- coding: utf-8 -*-
# Catslap
# Author: Luis A. González
# MIT License (view LICENSE file)
# Copyright (c) 2026


from catslap.utils import encoding as enc_util
from catslap.utils import text as text_util


class HtmlException(Exception):
  """
  HTML processing exception.
  """
  pass


def extract_image_data(image: str) -> tuple[str, str, bytes]:
  """
  Extracts metadata and bytes from a data URI embedded image.

  Args:
    image: Data URI string (data:<mime>;base64,<data>).

  Returns:
    Tuple (media_type, encoding, bytes) for the image.

  Raises:
    HtmlException: If the format, media type, or base64 are invalid.
  """
  idx0 = 5
  idx = image.find(';', idx0)
  if idx < 0:
    raise HtmlException('Invalid image media-type: ' + image[0:20] + '...')
  media_type = image[idx0:idx]
  idx2 = media_type.find('/')
  if idx2 < 0:
    raise HtmlException('Unsuppported image media-type: ' + media_type)
  idx0 = idx + 1
  idx = image.find(',', idx0)
  if idx < 0:
    raise HtmlException('Invalid image data encoding: ' + image[0:20] + '...')
  encoding = image[idx0:idx]
  if encoding.lower() != 'base64':
    raise HtmlException('Unsupported image data encoding: ' + encoding)
  image = image[idx+1:]
  try:
    base64bytes = enc_util.from_base64(image)
  except Exception:
    raise HtmlException('Invalid base64 image data: ' + image[0:20] + '...')
  return media_type, encoding, base64bytes


def parse_css(css: str) -> dict:
  """
  Parses an inline CSS block into a dictionary.

  Args:
    css: Style string (e.g., 'color: red; font-size: 12px;').

  Returns:
    Dictionary of properties normalized to lowercase.
  """
  stylemap = {}
  if css:
    lines = css.split(';')
    for line in lines:
      idx = line.find(':')
      if idx > 0:
        key = text_util.trim(line[0:idx]).lower()
        value = text_util.trim(line[idx+1:]).lower()
        stylemap[key] = value
  return stylemap


__COLOR_MAPPING = {
    'magenta': '#ff00ff',
    'fuchsia': '#ff00ff',
    'gray': '#808080',
    'darkred': '#8b0000',
    'brown': '#a52a2a',
    'firebrick': '#b22222',
    'crimson': '#dc143c',
    'red': '#ff0000',
    'tomato': '#ff6347',
    'coral': '#ff7f50',
    'indianred': '#cd5c5c',
    'lightcoral': '#f08080',
    'darksalmon': '#e9967a',
    'salmon': '#fa8072',
    'lightsalmon': '#ffa07a',
    'orangered': '#ff4500',
    'darkorange': '#ff8c00',
    'orange': '#ffa500',
    'gold': '#ffd700',
    'darkgoldenrod': '#b8860b',
    'goldenrod': '#daa520',
    'palegoldenrod': '#eee8aa',
    'darkkhaki': '#bdb76b',
    'khaki': '#f0e68c',
    'olive': '#808000',
    'yellow': '#ffff00',
    'yellowgreen': '#9acd32',
    'darkolivegreen': '#556b2f',
    'olivedrab': '#6b8e23',
    'lawngreen': '#7cfc00',
    'chartreuse': '#7fff00',
    'greenyellow': '#adff2f',
    'darkgreen': '#006400',
    'green': '#008000',
    'forestgreen': '#228b22',
    'lime': '#00ff00',
    'limegreen': '#32cd32',
    'lightgreen': '#90ee90',
    'palegreen': '#98fb98',
    'darkseagreen': '#8fbc8f',
    'mediumspringgreen': '#00fa9a',
    'springgreen': '#00ff7f',
    'seagreen': '#2e8b57',
    'mediumaquamarine': '#66cdaa',
    'mediumseagreen': '#3cb371',
    'lightseagreen': '#20b2aa',
    'darkslategray': '#2f4f4f',
    'teal': '#008080',
    'darkcyan': '#008b8b',
    'aqua': '#00ffff',
    'cyan': '#00ffff',
    'lightcyan': '#e0ffff',
    'darkturquoise': '#00ced1',
    'turquoise': '#40e0d0',
    'mediumturquoise': '#48d1cc',
    'paleturquoise': '#afeeee',
    'aquamarine': '#7fffd4',
    'powderblue': '#b0e0e6',
    'cadetblue': '#5f9ea0',
    'steelblue': '#4682b4',
    'cornflowerblue': '#6495ed',
    'deepskyblue': '#00bfff',
    'dodgerblue': '#1e90ff',
    'lightblue': '#add8e6',
    'skyblue': '#87ceeb',
    'lightskyblue': '#87cefa',
    'midnightblue': '#191970',
    'navy': '#000080',
    'darkblue': '#00008b',
    'mediumblue': '#0000cd',
    'blue': '#0000ff',
    'royalblue': '#4169e1',
    'blueviolet': '#8a2be2',
    'indigo': '#4b0082',
    'darkslateblue': '#483d8b',
    'slateblue': '#6a5acd',
    'mediumslateblue': '#7b68ee',
    'mediumpurple': '#9370db',
    'darkmagenta': '#8b008b',
    'darkviolet': '#9400d3',
    'darkorchid': '#9932cc',
    'mediumorchid': '#ba55d3',
    'purple': '#800080',
    'thistle': '#d8bfd8',
    'plum': '#dda0dd',
    'violet': '#ee82ee',
    'magenta/fuchsia': '#ff00ff',
    'orchid': '#da70d6',
    'mediumvioletred': '#c71585',
    'palevioletred': '#db7093',
    'deeppink': '#ff1493',
    'hotpink': '#ff69b4',
    'lightpink': '#ffb6c1',
    'pink': '#ffc0cb',
    'antiquewhite': '#faebd7',
    'beige': '#f5f5dc',
    'bisque': '#ffe4c4',
    'blanchedalmond': '#ffebcd',
    'wheat': '#f5deb3',
    'cornsilk': '#fff8dc',
    'lemonchiffon': '#fffacd',
    'lightgoldenrodyellow': '#fafad2',
    'lightyellow': '#ffffe0',
    'saddlebrown': '#8b4513',
    'sienna': '#a0522d',
    'chocolate': '#d2691e',
    'peru': '#cd853f',
    'sandybrown': '#f4a460',
    'burlywood': '#deb887',
    'tan': '#d2b48c',
    'rosybrown': '#bc8f8f',
    'moccasin': '#ffe4b5',
    'navajowhite': '#ffdead',
    'peachpuff': '#ffdab9',
    'mistyrose': '#ffe4e1',
    'lavenderblush': '#fff0f5',
    'linen': '#faf0e6',
    'oldlace': '#fdf5e6',
    'papayawhip': '#ffefd5',
    'seashell': '#fff5ee',
    'mintcream': '#f5fffa',
    'slategray': '#708090',
    'lightslategray': '#778899',
    'lightsteelblue': '#b0c4de',
    'lavender': '#e6e6fa',
    'floralwhite': '#fffaf0',
    'aliceblue': '#f0f8ff',
    'ghostwhite': '#f8f8ff',
    'honeydew': '#f0fff0',
    'ivory': '#fffff0',
    'azure': '#f0ffff',
    'snow': '#fffafa',
    'black': '#000000',
    'dimgray': '#696969',
    'dimgrey': '#696969',
    'grey': '#808080',
    'darkgray': '#a9a9a9',
    'darkgrey': '#a9a9a9',
    'silver': '#c0c0c0',
    'lightgray': '#d3d3d3',
    'lightgrey': '#d3d3d3',
    'gainsboro': '#dcdcdc',
    'whitesmoke': '#f5f5f5',
    'white': '#ffffff',
}


def get_rgb_color(color) -> str:
  """
  Converts a CSS color to RGB hex format (#rrggbb).

  Args:
    color: Color in CSS format (hex or name).

  Returns:
    Normalized hex color with '#'. If unknown, '#000000'.
  """
  color = text_util.trim(color).lower()
  if color.startswith('#'):
    if len(color) == 9:
      color = color[:-2]
    return color
  elif len(color) == 6 and text_util.is_hex(color):
    return color
  color = color.replace(' ', '')
  rgb = __COLOR_MAPPING.get(color)
  if rgb:
    return rgb
  return "#000000"
