#!/usr/bin/env bash

brt_image() {
  local file="${1:-}"
  local width=0
  local height=0
  local term_w term_h size

  if [[ -z "$file" ]]; then
    brt_error "Usage: brt -image <file> [-x cols] [-y rows]"
    brt_info "Renders images in the terminal (chafa, viu, imgcat, or ASCII fallback)"
    brt_info "Default size fills your terminal; -x/-y set size in character cells"
    exit 1
  fi

  shift
  while [[ $# -gt 0 ]]; do
    case "$1" in
      -x) width="$2"; shift 2 ;;
      -y) height="$2"; shift 2 ;;
      -w|--width) width="$2"; shift 2 ;;
      *)
        brt_error "Unknown option: $1"
        brt_info "Usage: brt -image <file> [-x cols] [-y rows]"
        exit 1
        ;;
    esac
  done

  if [[ ! -f "$file" ]]; then
    brt_error "File not found: ${file}"
    exit 1
  fi

  if ! [[ "$width" =~ ^[0-9]+$ && "$height" =~ ^[0-9]+$ ]]; then
    brt_error "-x and -y must be non-negative integers"
    exit 1
  fi

  read -r term_w term_h < <(brt_term_media_size "$width" "$height") || {
    brt_error "Could not determine image size"
    exit 1
  }
  size="${term_w}x${term_h}"

  brt_info "Rendering ${file} at ${size}..."

  # Kitty terminal
  if [[ "${TERM:-}" == *kitty* ]] && command -v kitty &>/dev/null; then
    kitty +kitten icat --transfer-mode=file --align=left --place "${size}@0x0" "$file" 2>/dev/null && return 0
  fi

  # iTerm2 imgcat
  if [[ "${TERM_PROGRAM:-}" == "iTerm.app" ]] && command -v imgcat &>/dev/null; then
    imgcat -W "${term_w}" "$file" && return 0
  fi

  # chafa — best general terminal renderer
  if command -v chafa &>/dev/null; then
    chafa -s "${size}" "$file"
    return 0
  fi

  # viu
  if command -v viu &>/dev/null; then
    viu -w "$term_w" -h "$term_h" "$file"
    return 0
  fi

  # macOS: sips + Python ASCII fallback
  if command -v sips &>/dev/null && command -v python3 &>/dev/null; then
    local tmp
    tmp=$(mktemp).ppm
    if sips -s format ppm "$file" --out "$tmp" &>/dev/null; then
      python3 "${BRT_LIB}/media.py" ascii "$tmp" "$term_w" "$term_h"
      rm -f "$tmp"
      brt_info "ASCII fallback — install chafa for color: brew install chafa"
      return 0
    fi
    rm -f "$tmp"
  fi

  brt_error "No image renderer available."
  brt_info "Install one of: chafa, viu  (brew install chafa)"
  exit 1
}
