defmodule Berrypod.Images.Optimizer do
  @moduledoc """
  Generates optimized image variants. Only creates sizes ≤ source dimensions.
  """

  require Logger

  alias Berrypod.Repo
  alias Berrypod.Media.Image, as: ImageSchema

  @all_widths [400, 800, 1200]
  @pregenerated_formats [:avif, :webp, :jpg]
  @thumb_size 200
  @max_stored_width 2000
  @storage_quality 90
  # Skip images smaller than this — they're placeholders or corrupt
  @min_image_bytes 100

  def cache_dir do
    Application.get_env(:berrypod, :image_cache_dir) ||
      Application.app_dir(:berrypod, "priv/static/image_cache")
  end

  def all_widths, do: @all_widths

  @doc """
  Returns the expected disk path for a variant file.
  Used to check the cache without loading the BLOB from the database.
  """
  def variant_path(image_id, width, format) do
    Path.join(cache_dir(), "#{image_id}-#{width}.#{format_ext(format)}")
  end

  @doc """
  Convert uploaded image to optimized WebP for storage.
  Images larger than #{@max_stored_width}px are resized down.
  Uses lossy WebP (quality #{@storage_quality}) for efficient storage.
  Returns {:ok, webp_data, width, height} or {:error, reason}.
  """
  def to_optimized_webp(image_data) when is_binary(image_data) do
    with {:ok, image} <- Image.from_binary(image_data),
         {width, _height, _} <- Image.shape(image),
         {:ok, resized} <- maybe_resize(image, width),
         {final_width, final_height, _} <- Image.shape(resized),
         {:ok, webp_data} <-
           Image.write(resized, :memory, suffix: ".webp", quality: @storage_quality) do
      {:ok, webp_data, final_width, final_height}
    end
  rescue
    e -> {:error, Exception.message(e)}
  end

  defp maybe_resize(image, width) when width <= @max_stored_width, do: {:ok, image}
  defp maybe_resize(image, _width), do: Image.thumbnail(image, @max_stored_width)

  @doc """
  Compute applicable widths from source dimensions.
  Only returns widths that are <= source_width (no upscaling).
  """
  def applicable_widths(source_width) when is_integer(source_width) do
    @all_widths
    |> Enum.filter(&(&1 <= source_width))
    |> case do
      [] -> [source_width]
      widths -> widths
    end
  end

  @doc """
  Process image and generate all applicable variants.
  Called by Oban worker.

  Handles both:
  - Pre-converted images (with source_width set)
  - Raw uploaded images (need conversion to WebP first)
  """
  def process_for_image(image_id) do
    # Load the image row and release the DB connection immediately,
    # so libvips processing doesn't block other queries.
    image = Repo.get(ImageSchema, image_id)

    case image do
      nil ->
        {:error, :not_found}

      %{data: nil} ->
        {:error, :no_data}

      %{is_svg: true} ->
        Repo.update!(ImageSchema.changeset(image, %{variants_status: "complete"}))
        {:ok, :svg_skipped}

      %{data: data} when byte_size(data) < @min_image_bytes ->
        {:error, :too_small}

      %{data: data, source_width: nil} ->
        # Raw image that needs conversion first
        process_raw_image(image, data)

      %{data: data, source_width: width} ->
        # Already converted to WebP with dimensions
        process_converted_image(image, data, width)
    end
  end

  # Process a raw uploaded image: convert to WebP, update DB, then generate variants
  defp process_raw_image(image, data) do
    case to_optimized_webp(data) do
      {:ok, webp_data, width, height} ->
        # Update the image record with converted data and dimensions
        updated =
          Repo.update!(
            ImageSchema.changeset(image, %{
              data: webp_data,
              content_type: "image/webp",
              file_size: byte_size(webp_data),
              source_width: width,
              source_height: height
            })
          )

        # Now generate variants with the converted data
        process_converted_image(updated, webp_data, width)

      {:error, reason} ->
        Logger.warning("Failed to convert image #{image.id}: #{inspect(reason)}")
        # Mark as complete anyway so we don't retry forever
        Repo.update!(ImageSchema.changeset(image, %{variants_status: "complete"}))
        {:error, reason}
    end
  end

  # Process an already-converted WebP image: generate variants
  defp process_converted_image(image, data, width) do
    File.mkdir_p!(cache_dir())

    # Write source WebP to disk so it can be served by Plug.Static
    source_path = Path.join(cache_dir(), "#{image.id}.webp")
    unless File.exists?(source_path), do: File.write!(source_path, data)

    with {:ok, vips_image} <- Image.from_binary(data) do
      widths = applicable_widths(width)

      all_tasks =
        [fn -> generate_thumbnail(vips_image, image.id) end] ++
          for w <- widths, fmt <- @pregenerated_formats do
            fn -> generate_variant(vips_image, image.id, w, fmt) end
          end

      # Cap concurrency to the number of CPU cores — keeps small
      # machines from choking while still saturating bigger ones.
      Task.async_stream(all_tasks, & &1.(),
        max_concurrency: System.schedulers_online(),
        timeout: :timer.seconds(120)
      )
      |> Stream.run()

      # Extract dominant colors for header images (used for contrast checking)
      maybe_extract_dominant_colors(image, vips_image)

      Repo.update!(ImageSchema.changeset(image, %{variants_status: "complete"}))
      {:ok, widths}
    end
  end

  # Extract and store dominant colors for header images.
  # Used to calculate text contrast warnings in the theme editor.
  defp maybe_extract_dominant_colors(%{image_type: "header"} = image, vips_image) do
    case Image.dominant_color(vips_image, top_n: 5) do
      {:ok, colors} when is_list(colors) ->
        # Wrap single color in list if needed
        colors = if is_list(hd(colors)), do: colors, else: [colors]
        Repo.update!(ImageSchema.changeset(image, %{dominant_colors: Jason.encode!(colors)}))

      _ ->
        :ok
    end
  end

  defp maybe_extract_dominant_colors(_image, _vips_image), do: :ok

  defp generate_thumbnail(image, id) do
    path = Path.join(cache_dir(), "#{id}-thumb.jpg")

    return_if_exists(path, fn ->
      with {:ok, thumb} <- Image.thumbnail(image, @thumb_size),
           {:ok, _} <- Image.write(thumb, path, quality: 80) do
        :ok
      end
    end)
  end

  defp generate_variant(image, id, width, format) do
    path = Path.join(cache_dir(), "#{id}-#{width}.#{format_ext(format)}")

    return_if_exists(path, fn ->
      with {:ok, resized} <- Image.thumbnail(image, width),
           {:ok, _} <- write_format(resized, path, format) do
        :ok
      end
    end)
  end

  defp return_if_exists(path, generate_fn) do
    if File.exists?(path), do: {:ok, :cached}, else: generate_fn.()
  end

  defp format_ext(:jpg), do: "jpg"
  defp format_ext(:webp), do: "webp"
  defp format_ext(:avif), do: "avif"

  defp write_format(image, path, :avif) do
    Image.write(image, path, effort: 5, minimize_file_size: true)
  end

  defp write_format(image, path, :webp) do
    Image.write(image, path, effort: 6, minimize_file_size: true)
  end

  defp write_format(image, path, :jpg) do
    Image.write(image, path, quality: 80, minimize_file_size: true)
  end

  @doc """
  Check if disk variants exist for an image.
  """
  def disk_variants_exist?(image_id, source_width) do
    widths = applicable_widths(source_width)
    source = File.exists?(Path.join(cache_dir(), "#{image_id}.webp"))
    thumb = File.exists?(Path.join(cache_dir(), "#{image_id}-thumb.jpg"))

    variants =
      Enum.all?(widths, fn w ->
        Enum.all?(@pregenerated_formats, fn fmt ->
          File.exists?(Path.join(cache_dir(), "#{image_id}-#{w}.#{format_ext(fmt)}"))
        end)
      end)

    source and thumb and variants
  end

  @doc """
  Process an image file and generate all variants to the specified directory.
  Used for both database images (to cache_dir) and mockups (to mockup_dir).
  Returns {:ok, source_width} or {:error, reason}.
  """
  def process_file(image_data, output_basename, output_dir) when is_binary(image_data) do
    File.mkdir_p!(output_dir)

    with {:ok, webp_data, source_width, _height} <- to_optimized_webp(image_data),
         {:ok, vips_image} <- Image.from_binary(webp_data) do
      widths = applicable_widths(source_width)

      all_tasks =
        [
          fn ->
            generate_variant_to_dir(
              vips_image,
              output_basename,
              output_dir,
              "thumb",
              :jpg,
              @thumb_size
            )
          end
        ] ++
          for w <- widths, fmt <- @pregenerated_formats do
            fn -> generate_variant_to_dir(vips_image, output_basename, output_dir, w, fmt, w) end
          end

      Task.async_stream(all_tasks, & &1.(),
        max_concurrency: System.schedulers_online(),
        timeout: :timer.seconds(120)
      )
      |> Stream.run()

      {:ok, source_width}
    end
  rescue
    e -> {:error, Exception.message(e)}
  end

  defp generate_variant_to_dir(image, basename, dir, size_label, format, resize_width) do
    filename = "#{basename}-#{size_label}.#{format_ext(format)}"
    path = Path.join(dir, filename)

    with {:ok, resized} <- Image.thumbnail(image, resize_width),
         {:ok, _} <- write_format(resized, path, format) do
      :ok
    end
  end
end
