import type { LaravelCms, MediaRecord } from "@/lib/laravel-cms/client";
import { ALLOWED_IMAGE_TYPES } from "@/lib/media/constants";
import { sniffImageType } from "@/lib/media/sniff";

/*
 * Puts the images of a blog export file into the CMS's media library through
 * `POST blog/admin/media`, then points the file at them, so the Laravel
 * import (which never downloads images) finds every one.
 *
 * Each distinct image is resolved once, in this order:
 *   1. Already served by the CMS at its `url` (or `sourceUrl`): left as is.
 *   2. In the media library with the same file name (and size, when both
 *      are known): reused, nothing uploaded. This is what makes running it
 *      twice safe.
 *   3. Otherwise its bytes are read from the local copy in storage
 *      (`file.storageKey`) or downloaded from `sourceUrl`, checked, and
 *      uploaded.
 * Every reference to a reused or uploaded image (featured, OG, CTA, author
 * photo, `images[]`) then gets the library's URL as `url` and `sourceUrl`,
 * and `src`/`srcset` attributes in article HTML that used an old address
 * are changed to it.
 *
 * No `server-only` here: the admin panel's import actions and
 * `npm run laravel -- upload-images` both use it.
 */

type FileInfo = {
  storageKey: string;
  filename: string;
  mimeType: string;
  size: number;
  width?: number | null;
  height?: number | null;
};

type Ref = {
  sourceUrl: string;
  alt?: string | null;
  title?: string | null;
  url?: string | null;
  file?: FileInfo | null;
};

type Found = { ref: Ref; label: string };

type Group = {
  key: string;
  refs: Found[];
  state: "on-cms" | "in-library" | "upload" | "unavailable";
  media?: MediaRecord;
  error?: string;
};

export type ImageUploadReport = {
  dryRun: boolean;
  /** Distinct image files the export file references. */
  images: number;
  /** Already served by the CMS; nothing to do. */
  onCms: number;
  /** Found in the media library and reused. */
  inLibrary: number;
  /** Uploaded (on a dry run: would be uploaded). */
  uploaded: number;
  /** Couldn't be read or uploaded. */
  failed: { label: string; source: string; error: string }[];
  /** Where each reused or uploaded image now points. */
  changed: { label: string; url: string }[];
};

export type ImageUploadOptions = {
  cms: Pick<LaravelCms, "apiUrl" | "uploadMedia" | "listMedia">;
  /** Only counts what would happen; uploads nothing and changes nothing. */
  dryRun: boolean;
  maxBytes: number;
  /** The local copy of a stored file (storage/uploads/<storageKey>), or null. */
  readStored?: (storageKey: string) => Promise<Uint8Array | null>;
  /** Hosts `sourceUrl` may be downloaded from. Undefined: any http(s) host. */
  downloadHosts?: string[];
  concurrency?: number;
  onProgress?: (done: number, total: number) => void;
};

const isRef = (value: unknown): value is Ref =>
  !!value &&
  typeof value === "object" &&
  typeof (value as Ref).sourceUrl === "string" &&
  "alt" in value;

/** Every image reference in the file, labelled like "some-slug › featuredImage". */
function findRefs(data: unknown) {
  const found: Found[] = [];
  const walk = (value: unknown, label: string) => {
    if (Array.isArray(value)) {
      value.forEach((item, i) => walk(item, `${label}[${i}]`));
      return;
    }
    if (!value || typeof value !== "object") return;
    if (isRef(value)) {
      found.push({ ref: value, label });
      return;
    }
    for (const [key, child] of Object.entries(value)) {
      walk(child, label ? `${label}.${key}` : key);
    }
  };
  const root = (data ?? {}) as Record<string, unknown>;
  const each = (list: unknown, prefix: (item: unknown) => string) => {
    if (!Array.isArray(list)) return;
    for (const item of list) walk(item, prefix(item));
  };
  const slugOf = (item: unknown) =>
    String((item as { slug?: unknown })?.slug ?? "?");
  each(root.posts, (item) => slugOf(item));
  each(root.authors, (item) => `author ${slugOf(item)}`);
  // Turn "slug.featuredImage" into "slug › featuredImage".
  for (const item of found) item.label = item.label.replace(".", " › ");
  return found;
}

const basename = (url: string) => {
  try {
    return decodeURIComponent(
      new URL(url, "http://x").pathname.split("/").pop() ?? "",
    );
  } catch {
    return url.split("/").pop() ?? "";
  }
};

async function pool<T>(
  items: T[],
  size: number,
  run: (item: T) => Promise<void>,
) {
  let next = 0;
  await Promise.all(
    Array.from({ length: Math.min(size, items.length) }, async () => {
      while (next < items.length) await run(items[next++]);
    }),
  );
}

export async function uploadExportImages(
  input: unknown,
  options: ImageUploadOptions,
): Promise<{ data: unknown; report: ImageUploadReport }> {
  const data = structuredClone(input);
  const origin = new URL(options.cms.apiUrl).origin;
  const absolute = (url: string) => new URL(url, origin).toString();
  const onCmsHost = (url: string) => {
    try {
      return new URL(url, origin).origin === origin;
    } catch {
      return false;
    }
  };

  // One group per distinct file.
  const groups = new Map<string, Group>();
  for (const found of findRefs(data)) {
    const { ref } = found;
    const key = ref.file?.storageKey || ref.url || ref.sourceUrl;
    const group = groups.get(key) ?? {
      key,
      refs: [],
      state: "upload" as const,
    };
    group.refs.push(found);
    groups.set(key, group);
  }

  // The media library, indexed by file name, loaded once.
  let library: Promise<Map<string, MediaRecord[]>> | null = null;
  const loadLibrary = async () => {
    const index = new Map<string, MediaRecord[]>();
    for (let page = 1; page <= 50; page++) {
      // A library that can't be listed only means nothing is reused.
      const result = await options.cms
        .listMedia({ page, pageSize: 60 })
        .catch(() => null);
      if (!result) break;
      const { items, lastPage } = result;
      for (const item of items) {
        for (const name of new Set([item.filename, basename(item.url)])) {
          const key = name.toLowerCase();
          if (key) index.set(key, [...(index.get(key) ?? []), item]);
        }
      }
      if (page >= lastPage || items.length === 0) break;
    }
    return index;
  };

  const status = (url: string) =>
    fetch(url, {
      method: "HEAD",
      cache: "no-store",
      signal: AbortSignal.timeout(15_000),
    }).then(
      (response) => response.status,
      () => 0,
    );

  async function download(url: string) {
    const parsed = new URL(url);
    if (!/^https?:$/.test(parsed.protocol))
      throw new Error("not an http(s) URL");
    const allowed = (host: string) =>
      !options.downloadHosts ||
      host === new URL(origin).hostname ||
      options.downloadHosts.includes(host);
    if (!allowed(parsed.hostname))
      throw new Error(`downloads from ${parsed.hostname} aren't allowed`);
    const response = await fetch(url, {
      cache: "no-store",
      signal: AbortSignal.timeout(30_000),
    });
    if (!allowed(new URL(response.url || url).hostname))
      throw new Error("redirected to a host that isn't allowed");
    if (!response.ok) throw new Error(`download answered ${response.status}`);
    const length = Number(response.headers.get("content-length"));
    if (length > options.maxBytes) throw new Error("the image is too large");
    const bytes = new Uint8Array(await response.arrayBuffer());
    if (bytes.byteLength > options.maxBytes)
      throw new Error("the image is too large");
    return bytes;
  }

  async function bytesOf(ref: Ref) {
    const key = ref.file?.storageKey;
    if (key && options.readStored) {
      const stored = await options.readStored(key);
      if (stored && (!ref.file?.size || stored.byteLength === ref.file.size))
        return stored;
    }
    return download(ref.sourceUrl);
  }

  async function resolve(group: Group) {
    const { ref } = group.refs[0];

    // 1. Already served by the CMS.
    for (const candidate of [ref.url, ref.sourceUrl]) {
      if (candidate && onCmsHost(candidate)) {
        if ((await status(absolute(candidate))) === 200) {
          group.state = "on-cms";
          return;
        }
      }
    }

    // 2. In the media library.
    const filename = ref.file?.filename || basename(ref.url || ref.sourceUrl);
    library ??= loadLibrary();
    const match = (await library)
      .get(filename.toLowerCase())
      ?.find(
        (item) => !item.size || !ref.file?.size || item.size === ref.file.size,
      );
    if (match) {
      group.state = "in-library";
      group.media = match;
      return;
    }

    // 3. Upload.
    let bytes: Uint8Array;
    try {
      bytes = await bytesOf(ref);
    } catch (error) {
      group.state = "unavailable";
      group.error = error instanceof Error ? error.message : String(error);
      return;
    }
    const mimeType = sniffImageType(bytes);
    if (!mimeType || !(mimeType in ALLOWED_IMAGE_TYPES)) {
      group.state = "unavailable";
      group.error = "not a JPG, PNG, WebP or AVIF image";
      return;
    }
    if (options.dryRun) return;

    const alt = group.refs.map((item) => item.ref.alt ?? "").find(Boolean);
    const title = group.refs.map((item) => item.ref.title ?? "").find(Boolean);
    try {
      group.media = await options.cms.uploadMedia({
        filename,
        bytes,
        mimeType,
        alt,
        title,
      });
    } catch (error) {
      group.state = "unavailable";
      group.error = `upload failed: ${error instanceof Error ? error.message : String(error)}`;
    }
  }

  const list = [...groups.values()];
  let done = 0;
  await pool(list, options.concurrency ?? 4, async (group) => {
    await resolve(group);
    options.onProgress?.(++done, list.length);
  });

  // Point every reference at the library's copy.
  const replaced = new Map<string, string>(); // old address → new URL
  const changed: ImageUploadReport["changed"] = [];
  for (const group of list) {
    if (!group.media) continue;
    const media = group.media;
    const url = absolute(media.url);
    const path = new URL(url).pathname;
    const storageKey =
      media.storageKey ??
      (path.startsWith("/uploads/")
        ? decodeURIComponent(path.slice("/uploads/".length))
        : null);
    for (const { ref, label } of group.refs) {
      for (const old of [ref.url, ref.sourceUrl]) {
        if (!old || old === url) continue;
        replaced.set(old, url);
        if (old.startsWith("/")) replaced.set(absolute(old), url);
      }
      const previous = ref.file;
      ref.url = url;
      ref.sourceUrl = url;
      ref.file = storageKey
        ? {
            storageKey,
            filename: media.filename || previous?.filename || basename(url),
            mimeType: media.mimeType || previous?.mimeType || "image/webp",
            size: media.size || previous?.size || 0,
            width: media.width ?? previous?.width ?? null,
            height: media.height ?? previous?.height ?? null,
          }
        : null;
      changed.push({ label, url });
    }
  }

  if (replaced.size) {
    const swap = (value: string) => replaced.get(value.trim()) ?? value;
    const posts = (data as { posts?: { content?: unknown }[] }).posts ?? [];
    for (const post of posts) {
      if (typeof post.content !== "string") continue;
      post.content = post.content.replace(
        /\b(src|srcset)=(["'])(.*?)\2/gi,
        (_, attr: string, quote: string, value: string) => {
          const next =
            attr.toLowerCase() === "srcset"
              ? value
                  .split(",")
                  .map((part) => {
                    const [src, ...rest] = part.trim().split(/\s+/);
                    return [swap(src), ...rest].join(" ");
                  })
                  .join(", ")
              : swap(value);
          return `${attr}=${quote}${next}${quote}`;
        },
      );
    }
  }

  const count = (state: Group["state"]) =>
    list.filter((group) => group.state === state).length;
  return {
    data,
    report: {
      dryRun: options.dryRun,
      images: list.length,
      onCms: count("on-cms"),
      inLibrary: count("in-library"),
      uploaded: count("upload"),
      failed: list
        .filter((group) => group.state === "unavailable")
        .map((group) => ({
          label:
            group.refs[0].label +
            (group.refs.length > 1 ? ` (+${group.refs.length - 1} more)` : ""),
          source: group.refs[0].ref.sourceUrl,
          error: group.error ?? "unavailable",
        })),
      changed,
    },
  };
}
