import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";

function identifier(value) {
  return value.replaceAll(/[^A-Za-z0-9_$]/g, "_");
}

function schemaType(schema, namedSchemas = []) {
  if (!schema || typeof schema !== "object") return "unknown";
  if (schema.$ref) return identifier(schema.$ref.split("/").at(-1));
  const named = namedSchemas.find(([, candidate]) => JSON.stringify(candidate) === JSON.stringify(schema));
  if (named) return identifier(named[0]);
  if (Object.hasOwn(schema, "const")) return JSON.stringify(schema.const);
  if (schema.enum) return schema.enum.map((value) => JSON.stringify(value)).join(" | ");
  if (schema.anyOf) return schema.anyOf.map((item) => schemaType(item, namedSchemas)).join(" | ");
  if (schema.oneOf) return schema.oneOf.map((item) => schemaType(item, namedSchemas)).join(" | ");
  if (Array.isArray(schema.type)) {
    return schema.type.map((type) => schemaType({ ...schema, type }, namedSchemas)).join(" | ");
  }
  if (schema.type === "array") return `Array<${schemaType(schema.items, namedSchemas)}>`;
  if (schema.type === "boolean") return "boolean";
  if (schema.type === "integer" || schema.type === "number") return "number";
  if (schema.type === "null") return "null";
  if (schema.type === "string") return "string";
  if (schema.type === "object" || schema.properties) {
    const required = new Set(schema.required ?? []);
    const fields = Object.entries(schema.properties ?? {}).map(
      ([name, child]) => `  ${JSON.stringify(name)}${required.has(name) ? "" : "?"}: ${schemaType(child, namedSchemas)};`,
    );
    if (!fields.length && schema.additionalProperties && typeof schema.additionalProperties === "object") {
      return `Record<string, ${schemaType(schema.additionalProperties, namedSchemas)}>`;
    }
    if (!fields.length && schema.additionalProperties === true) return "Record<string, unknown>";
    return fields.length ? `{\n${fields.join("\n")}\n}` : "Record<string, never>";
  }
  return "unknown";
}

function operationResult(operation, namedSchemas) {
  const response = operation.responses?.["200"];
  if (!response) return "unknown";
  if (response.content) {
    const media = response.content["application/json"] ?? response.content["text/event-stream"] ?? Object.values(response.content)[0];
    if (media?.schema) return media.schema.format === "binary" ? "Blob" : schemaType(media.schema, namedSchemas);
  }
  return response.schema ? schemaType(response.schema, namedSchemas) : "unknown";
}

function operationBodyType(operation, namedSchemas) {
  const content = operation.requestBody?.content;
  const jsonSchema = content?.["application/json"]?.schema;
  if (jsonSchema) return schemaType(jsonSchema, namedSchemas);
  if (content?.["multipart/form-data"]?.schema) return "FormData";
  return undefined;
}

function operationRequestMediaType(operation) {
  const content = operation.requestBody?.content;
  if (content?.["application/json"]) return "application/json";
  if (content?.["multipart/form-data"]) return "multipart/form-data";
  return undefined;
}

function operationReturnsBinary(operation) {
  return Object.values(operation.responses?.["200"]?.content ?? {})
    .some((media) => media?.schema?.format === "binary");
}

function operationMediaType(operation) {
  const content = operation.responses?.["200"]?.content;
  if (!content) return undefined;
  return Object.keys(content)[0];
}

function operations(document) {
  const result = [];
  for (const [path, pathItem] of Object.entries(document.paths ?? {})) {
    for (const method of ["get", "post", "put", "patch", "delete"]) {
      const operation = pathItem[method];
      if (operation?.operationId) result.push({ method, operation, path });
    }
  }
  return result.sort((left, right) => left.operation.operationId.localeCompare(right.operation.operationId));
}

export function generateClient(input, output) {
  const document = JSON.parse(readFileSync(input, "utf8"));
  const schemas = Object.entries(document.components?.schemas ?? {})
    .map(([key, schema]) => [schema.title ?? key, schema])
    .sort(([left], [right]) => left.localeCompare(right));
  const types = [
    "// Generated from openapi/openapi.json. Do not edit by hand.",
    ...schemas.map(([name, schema]) => `export type ${identifier(name)} = ${schemaType(schema)};`),
  ].join("\n\n");

  const operationList = operations(document);
  const builtInTypes = new Set(["Blob", "FormData", "boolean", "number", "string", "unknown"]);
  const importedTypes = [...new Set(operationList.flatMap(({ operation }) => [
    operationResult(operation, schemas),
    operationBodyType(operation, schemas),
  ]).filter((type) => type && !builtInTypes.has(type) && /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(type)))];
  const sdk = [
    "// Generated from openapi/openapi.json. Do not edit by hand.",
    importedTypes.length ? `import type { ${importedTypes.join(", ")} } from "./types.gen.js";` : "",
    "export interface ClientOptions { baseUrl?: string; fetch?: typeof globalThis.fetch; headers?: HeadersInit; }",
    ...operationList.map(({ method, operation, path }) => {
      const resultType = operationResult(operation, schemas);
      const bodyType = operationBodyType(operation, schemas);
      const requestMediaType = operationRequestMediaType(operation);
      if (operationMediaType(operation) === "text/event-stream") {
        return `export function ${identifier(operation.operationId)}(options: Pick<ClientOptions, "baseUrl"> = {}): string {\n  return \`${"${options.baseUrl ?? \"\"}"}${path}\`;\n}`;
      }
      if (bodyType) {
        const bodyExpression = requestMediaType === "application/json" ? "JSON.stringify(body)" : "body";
        const contentType = requestMediaType === "application/json" ? '\n  headers.set("Content-Type", "application/json");' : "";
        return `export async function ${identifier(operation.operationId)}(body: ${bodyType}, options: ClientOptions = {}): Promise<${resultType}> {\n  const request = options.fetch ?? globalThis.fetch;\n  const headers = new Headers(options.headers);${contentType}\n  const response = await request(\`${"${options.baseUrl ?? \"\"}"}${path}\`, { body: ${bodyExpression}, method: "${method.toUpperCase()}", headers });\n  if (!response.ok) throw new Error(\`HTTP ${"${response.status}"}\`);\n  return response.json() as Promise<${resultType}>;\n}`;
      }
      const responseReader = operationReturnsBinary(operation) ? "response.blob()" : "response.json()";
      return `export async function ${identifier(operation.operationId)}(options: ClientOptions = {}): Promise<${resultType}> {\n  const request = options.fetch ?? globalThis.fetch;\n  const response = await request(\`${"${options.baseUrl ?? \"\"}"}${path}\`, { method: "${method.toUpperCase()}", headers: options.headers ?? {} });\n  if (!response.ok) throw new Error(\`HTTP ${"${response.status}"}\`);\n  return ${responseReader} as Promise<${resultType}>;\n}`;
    }),
    "",
  ].filter(Boolean).join("\n\n");

  mkdirSync(output, { recursive: true });
  writeFileSync(resolve(output, "sdk.gen.ts"), `${sdk}\n`);
  writeFileSync(resolve(output, "types.gen.ts"), `${types}\n`);
}
