import { getImage, type GyazoAPIError } from "../deno-gyazo/mod.ts";
import { getGyazoToken } from "../scrapbox-userscript-std/rest.ts";
import { pooledMap } from "jsr:@std/async@1/pool";
import { createOk, isErr, unwrapOk, type Result } from "npm:option-t@50/plain_result";

export interface ImageResult {
  url: string;
  text: string;
}

export const getOCRs = (
  images: Iterable<string | URL> | AsyncIterable<string | URL>,
  accessToken: string,
): AsyncIterableIterator<Result<ImageResult, GyazoAPIError>> => pooledMap(
  10,
  images,
  async (image): Promise<Result<ImageResult, GyazoAPIError>> => {
    const id = `${image}`.match(/\/([^\/]+)$/)?.[1];
    if (!id) throw new Error(`Could not find Gyazo ID from "${image}"`);
    const result = await getImage(id, { accessToken });
    if (isErr(result)) return result;
    const { permalink_url, ocr } = unwrapOk(result);
    return createOk({ url: permalink_url, text: ocr?.description || "" });
  },
);