import { isPlainObject } from '@trpc/server/vendor/is-plain-object';
import {
  assertNever,
  emptyObject,
  isAsyncIterable,
  isFunction,
  isObject,
  run,
} from '../utils';
import { iteratorResource } from './utils/asyncIterable';
import type { Deferred } from './utils/createDeferred';
import { createDeferred } from './utils/createDeferred';
import { makeAsyncResource, makeResource } from './utils/disposable';
import { mergeAsyncIterables } from './utils/mergeAsyncIterables';
import { readableStreamFrom } from './utils/readableStreamFrom';
import { PING_SYM, withPing } from './utils/withPing';

/**
 * A subset of the standard ReadableStream properties needed by tRPC internally.
 * @see ReadableStream from lib.dom.d.ts
 */
export type WebReadableStreamEsque = {
  getReader: () => ReadableStreamDefaultReader<Uint8Array>;
};

export type NodeJSReadableStreamEsque = {
  on(
    eventName: string | symbol,
    listener: (...args: any[]) => void,
  ): NodeJSReadableStreamEsque;
};

// ---------- types
const CHUNK_VALUE_TYPE_PROMISE = 0;
type CHUNK_VALUE_TYPE_PROMISE = typeof CHUNK_VALUE_TYPE_PROMISE;
const CHUNK_VALUE_TYPE_ASYNC_ITERABLE = 1;
type CHUNK_VALUE_TYPE_ASYNC_ITERABLE = typeof CHUNK_VALUE_TYPE_ASYNC_ITERABLE;

const PROMISE_STATUS_FULFILLED = 0;
type PROMISE_STATUS_FULFILLED = typeof PROMISE_STATUS_FULFILLED;
const PROMISE_STATUS_REJECTED = 1;
type PROMISE_STATUS_REJECTED = typeof PROMISE_STATUS_REJECTED;

const ASYNC_ITERABLE_STATUS_RETURN = 0;
type ASYNC_ITERABLE_STATUS_RETURN = typeof ASYNC_ITERABLE_STATUS_RETURN;
const ASYNC_ITERABLE_STATUS_YIELD = 1;
type ASYNC_ITERABLE_STATUS_YIELD = typeof ASYNC_ITERABLE_STATUS_YIELD;
const ASYNC_ITERABLE_STATUS_ERROR = 2;
type ASYNC_ITERABLE_STATUS_ERROR = typeof ASYNC_ITERABLE_STATUS_ERROR;

type ChunkDefinitionKey =
  // root should be replaced
  | null
  // at array path
  | number
  // at key path
  | string;

type ChunkIndex = number & { __chunkIndex: true };
type ChunkValueType =
  | CHUNK_VALUE_TYPE_PROMISE
  | CHUNK_VALUE_TYPE_ASYNC_ITERABLE;
type ChunkDefinition = [
  key: ChunkDefinitionKey,
  type: ChunkValueType,
  chunkId: ChunkIndex,
];
type EncodedValue = [
  // data
  [unknown] | [],
  // chunk descriptions
  ...ChunkDefinition[],
];

type Head = Record<string, EncodedValue>;
type PromiseChunk =
  | [
      chunkIndex: ChunkIndex,
      status: PROMISE_STATUS_FULFILLED,
      value: EncodedValue,
    ]
  | [chunkIndex: ChunkIndex, status: PROMISE_STATUS_REJECTED, error: unknown];
type IterableChunk =
  | [
      chunkIndex: ChunkIndex,
      status: ASYNC_ITERABLE_STATUS_RETURN,
      value: EncodedValue,
    ]
  | [
      chunkIndex: ChunkIndex,
      status: ASYNC_ITERABLE_STATUS_YIELD,
      value: EncodedValue,
    ]
  | [
      chunkIndex: ChunkIndex,
      status: ASYNC_ITERABLE_STATUS_ERROR,
      error: unknown,
    ];
type ChunkData = PromiseChunk | IterableChunk;
type PlaceholderValue = 0 & { __placeholder: true };
export function isPromise(value: unknown): value is Promise<unknown> {
  return (
    (isObject(value) || isFunction(value)) &&
    typeof value?.['then'] === 'function' &&
    typeof value?.['catch'] === 'function'
  );
}

type Serialize = (value: any) => any;
type Deserialize = (value: any) => any;

type PathArray = readonly (string | number)[];
export type ProducerOnError = (opts: {
  error: unknown;
  path: PathArray;
}) => void;
export interface JSONLProducerOptions {
  serialize?: Serialize;
  data: Record<string, unknown> | unknown[];
  onError?: ProducerOnError;
  formatError?: (opts: { error: unknown; path: PathArray }) => unknown;
  maxDepth?: number;
  /**
   * Interval in milliseconds to send a ping to the client to keep the connection alive
   * This will be sent as a whitespace character
   * @default undefined
   */
  pingMs?: number;
}

class MaxDepthError extends Error {
  constructor(public path: (string | number)[]) {
    super('Max depth reached at path: ' + path.join('.'));
  }
}

/**
 * A promise or iterable found while encoding a line. It starts only once that
 * line is serialized; if the line fails, it's dropped instead.
 */
interface PendingChunk {
  iterable: AsyncIterable<string, void>;
  drop: () => void;
}

/**
 * Yields the stream's lines, each serialized where it was made, so a value
 * that can't be serialized fails only the promise or iterable it belongs to
 */
async function* createBatchStreamProducer(
  opts: JSONLProducerOptions,
): AsyncIterable<string | typeof PING_SYM, void> {
  const { data } = opts;
  let counter = 0 as ChunkIndex;
  const placeholder = 0 as PlaceholderValue;

  const mergedIterables = mergeAsyncIterables<string>();

  /**
   * Serializes the chunk `build` returns, then starts the promises and
   * iterables found in it. If that fails, or the stream has stopped, they're
   * dropped, so nothing keeps the response open for a value the client never
   * receives.
   */
  function line(build: (pending: PendingChunk[]) => Head | ChunkData) {
    const pending: PendingChunk[] = [];
    try {
      const chunk = build(pending);
      const result = JSON.stringify(
        opts.serialize ? opts.serialize(chunk) : chunk,
      );
      for (const it of pending) {
        if (!mergedIterables.add(it.iterable)) {
          it.drop();
        }
      }
      return result;
    } catch (cause) {
      for (const it of pending) {
        it.drop();
      }
      throw cause;
    }
  }

  function registerAsync(
    pending: PendingChunk[],
    callback: (idx: ChunkIndex) => AsyncIterable<string, void>,
    drop: () => void,
  ) {
    const idx = counter++ as ChunkIndex;

    pending.push({ iterable: callback(idx), drop });

    return idx;
  }

  function reportError(path: (string | number)[]) {
    return (cause: unknown) => {
      opts.onError?.({ error: cause, path });
    };
  }

  function encodePromise(
    promise: Promise<unknown>,
    path: (string | number)[],
    pending: PendingChunk[],
  ) {
    return registerAsync(
      pending,
      async function* (idx) {
        const error = checkMaxDepth(path);
        if (error) {
          // Catch any errors from the original promise to ensure they're reported
          promise.catch(reportError(path));
          // Replace the promise with a rejected one containing the max depth error
          promise = Promise.reject(error);
        }
        try {
          const next = await promise;
          yield line((children) => [
            idx,
            PROMISE_STATUS_FULFILLED,
            encode(next, path, children),
          ]);
        } catch (cause) {
          opts.onError?.({ error: cause, path });
          yield line(() => [
            idx,
            PROMISE_STATUS_REJECTED,
            opts.formatError?.({ error: cause, path }),
          ]);
        }
      },
      () => {
        // nobody awaits it now, so report a rejection rather than leave it unhandled
        promise.catch(reportError(path));
      },
    );
  }
  function encodeAsyncIterable(
    iterable: AsyncIterable<unknown>,
    path: (string | number)[],
    pending: PendingChunk[],
  ) {
    return registerAsync(
      pending,
      async function* (idx) {
        const error = checkMaxDepth(path);
        if (error) {
          throw error;
        }
        const iterator = iteratorResource(iterable);
        // An error from cleaning up is reported, not thrown, so it can't fail
        // the other calls in the stream
        await using _cleanup = makeAsyncResource({}, async () => {
          try {
            await using _iterator = iterator;
          } catch (cause) {
            opts.onError?.({ error: cause, path });
          }
        });

        try {
          while (true) {
            const next = await iterator.next();
            if (next.done) {
              yield line((children) => [
                idx,
                ASYNC_ITERABLE_STATUS_RETURN,
                encode(next.value, path, children),
              ]);
              break;
            }
            yield line((children) => [
              idx,
              ASYNC_ITERABLE_STATUS_YIELD,
              encode(next.value, path, children),
            ]);
          }
        } catch (cause) {
          opts.onError?.({ error: cause, path });

          yield line(() => [
            idx,
            ASYNC_ITERABLE_STATUS_ERROR,
            opts.formatError?.({ error: cause, path }),
          ]);
        }
      },
      () => {
        // never started, so there's nothing to clean up
      },
    );
  }
  function checkMaxDepth(path: (string | number)[]) {
    if (opts.maxDepth && path.length > opts.maxDepth) {
      return new MaxDepthError(path);
    }
    return null;
  }
  function encodeAsync(
    value: unknown,
    path: (string | number)[],
    pending: PendingChunk[],
  ): null | [type: ChunkValueType, chunkId: ChunkIndex] {
    if (isPromise(value)) {
      return [CHUNK_VALUE_TYPE_PROMISE, encodePromise(value, path, pending)];
    }
    if (isAsyncIterable(value)) {
      if (opts.maxDepth && path.length >= opts.maxDepth) {
        throw new Error('Max depth reached');
      }
      return [
        CHUNK_VALUE_TYPE_ASYNC_ITERABLE,
        encodeAsyncIterable(value, path, pending),
      ];
    }
    return null;
  }
  function encode(
    value: unknown,
    path: (string | number)[],
    pending: PendingChunk[],
  ): EncodedValue {
    if (value === undefined) {
      return [[]];
    }
    const reg = encodeAsync(value, path, pending);
    if (reg) {
      return [[placeholder], [null, ...reg]];
    }

    if (!isPlainObject(value)) {
      return [[value]];
    }

    const newObj: Record<string, unknown> = emptyObject();
    const asyncValues: ChunkDefinition[] = [];
    for (const [key, item] of Object.entries(value)) {
      const transformed = encodeAsync(item, [...path, key], pending);
      if (!transformed) {
        newObj[key] = item;
        continue;
      }
      newObj[key] = placeholder;
      asyncValues.push([key, ...transformed]);
    }
    return [[newObj], ...asyncValues];
  }

  yield line((children) => {
    const newHead: Head = emptyObject();
    for (const [key, item] of Object.entries(data)) {
      newHead[key] = encode(item, [key], children);
    }
    return newHead;
  });

  let iterable: AsyncIterable<string | typeof PING_SYM, void> = mergedIterables;
  if (opts.pingMs) {
    iterable = withPing(mergedIterables, opts.pingMs);
  }

  for await (const value of iterable) {
    yield value;
  }
}
/**
 * JSON Lines stream producer
 * @see https://jsonlines.org/
 */
export function jsonlStreamProducer(opts: JSONLProducerOptions) {
  return readableStreamFrom(createBatchStreamProducer(opts))
    .pipeThrough(
      new TransformStream({
        transform(chunk, controller) {
          controller.enqueue(chunk === PING_SYM ? ' ' : chunk + '\n');
        },
      }),
    )
    .pipeThrough(new TextEncoderStream());
}

class AsyncError extends Error {
  constructor(public readonly data: unknown) {
    super('Received error from server');
  }
}
export type ConsumerOnError = (opts: { error: unknown }) => void;
export type ConsumerOnSettled = (opts: { key: string }) => void;

const nodeJsStreamToReaderEsque = (source: NodeJSReadableStreamEsque) => {
  return {
    getReader() {
      const stream = new ReadableStream<Uint8Array>({
        start(controller) {
          source.on('data', (chunk) => {
            controller.enqueue(chunk);
          });
          source.on('end', () => {
            controller.close();
          });
          source.on('error', (error) => {
            controller.error(error);
          });
        },
      });
      return stream.getReader();
    },
  };
};

function createLineAccumulator(
  from: NodeJSReadableStreamEsque | WebReadableStreamEsque,
) {
  const reader =
    'getReader' in from
      ? from.getReader()
      : nodeJsStreamToReaderEsque(from).getReader();

  let lineAggregate = '';

  return new ReadableStream({
    async pull(controller) {
      const { done, value } = await reader.read();

      if (done) {
        controller.close();
      } else {
        controller.enqueue(value);
      }
    },
    cancel() {
      return reader.cancel();
    },
  })
    .pipeThrough(new TextDecoderStream())
    .pipeThrough(
      new TransformStream<string, string>({
        transform(chunk, controller) {
          lineAggregate += chunk;
          const parts = lineAggregate.split('\n');
          lineAggregate = parts.pop() ?? '';
          for (const part of parts) {
            controller.enqueue(part);
          }
        },
      }),
    );
}
function createConsumerStream<THead>(
  from: NodeJSReadableStreamEsque | WebReadableStreamEsque,
) {
  const stream = createLineAccumulator(from);

  let sentHead = false;
  return stream.pipeThrough(
    new TransformStream<string, ChunkData | THead>({
      transform(line, controller) {
        if (!sentHead) {
          const head = JSON.parse(line);
          controller.enqueue(head as THead);
          sentHead = true;
        } else {
          const chunk: ChunkData = JSON.parse(line);
          controller.enqueue(chunk);
        }
      },
    }),
  );
}

/**
 * Creates a handler for managing stream controllers and their lifecycle
 */
function createStreamsManager(opts: {
  abortController: AbortController;
  onSettled: ConsumerOnSettled | null;
}) {
  let terminalState:
    | { type: 'closed' }
    | { type: 'errored'; reason: unknown }
    | undefined;
  const controllerMap = new Map<
    ChunkIndex,
    ReturnType<typeof createStreamController>
  >();
  /** The head key each decoded chunk is under */
  const headKeys = new Map<ChunkIndex, string>();
  /** How many chunks under each head key are still open */
  const openCounts = new Map<string, number>();
  const settledKeys = new Set<string>();

  /**
   * Checks if there are no pending controllers or deferred promises
   */
  function isEmpty() {
    return Array.from(controllerMap.values()).every((c) => c.closed);
  }

  /**
   * Reports a head key as settled, once, when none of its chunks is open
   */
  function settleIfIdle(key: string) {
    if (openCounts.get(key) || settledKeys.has(key)) {
      return;
    }
    settledKeys.add(key);
    opts.onSettled?.({ key });
  }

  /**
   * Creates a stream controller
   */
  function createStreamController(chunkId: ChunkIndex) {
    let originalController: ReadableStreamDefaultController<ChunkData>;
    const stream = new ReadableStream<ChunkData>({
      start(controller) {
        originalController = controller;
      },
    });

    const streamController = {
      enqueue: (v: ChunkData) => originalController.enqueue(v),
      close: () => {
        originalController.close();

        clear();

        const key = headKeys.get(chunkId);
        if (key !== undefined) {
          openCounts.set(key, (openCounts.get(key) ?? 1) - 1);
          settleIfIdle(key);
        }
        if (isEmpty()) {
          opts.abortController.abort();
        }
      },
      closed: false,
      // A lazy iterable may acquire its reader after the source closes or errors.
      getReaderResource: () => {
        const reader = stream.getReader();

        return makeResource(reader, () => {
          streamController.close();
          reader.releaseLock();
        });
      },
      error: (reason: unknown) => {
        originalController.error(reason);

        clear();
      },
    };
    function clear() {
      Object.assign(streamController, {
        closed: true,
        close: () => {
          // noop
        },
        enqueue: () => {
          // noop
        },
        error: () => {
          // noop
        },
      });
    }

    return streamController;
  }

  /**
   * Gets or creates a stream controller
   */
  function getOrCreate(chunkId: ChunkIndex) {
    let c = controllerMap.get(chunkId);
    if (!c) {
      c = createStreamController(chunkId);
      controllerMap.set(chunkId, c);
      // Buffered values can reveal nested async values after the source ends.
      if (terminalState?.type === 'closed') {
        c.close();
      } else if (terminalState?.type === 'errored') {
        c.error(terminalState.reason);
      }
    }
    return c;
  }

  /**
   * Cancels all pending controllers and rejects deferred promises
   */
  function cancelAll(reason: unknown) {
    if (terminalState) {
      return;
    }
    terminalState = { type: 'errored', reason };
    for (const controller of controllerMap.values()) {
      controller.error(reason);
    }
  }

  /**
   * Closes all pending controllers to preserve buffered data
   */
  function closeAll() {
    if (terminalState) {
      return;
    }
    terminalState = { type: 'closed' };
    for (const controller of controllerMap.values()) {
      controller.close();
    }
  }

  /**
   * Gets or creates the stream controller of a chunk decoded under a head key.
   * A chunk is decoded while its parent is still open, so the head key can't
   * settle before its last chunk closes, unless the source has already ended
   * and nothing is left to stream.
   */
  function getOrCreateUnder(chunkId: ChunkIndex, key: string) {
    const c = getOrCreate(chunkId);
    if (!headKeys.has(chunkId)) {
      headKeys.set(chunkId, key);
      if (!c.closed) {
        openCounts.set(key, (openCounts.get(key) ?? 0) + 1);
      }
    }
    return c;
  }

  return {
    getOrCreate,
    getOrCreateUnder,
    settleIfIdle,
    cancelAll,
    closeAll,
  };
}

/**
 * JSON Lines stream consumer
 * @see https://jsonlines.org/
 */
export async function jsonlStreamConsumer<THead>(opts: {
  from: NodeJSReadableStreamEsque | WebReadableStreamEsque;
  deserialize?: Deserialize;
  onError?: ConsumerOnError;
  formatError?: (opts: { error: unknown }) => Error;
  /**
   * This `AbortController` will be triggered when there are no more listeners to the stream.
   */
  abortController: AbortController;
  /**
   * Called with a head key once every streamed part under it has closed:
   * each promise has settled and each async iterable has finished or been
   * cancelled.
   */
  onSettled?: ConsumerOnSettled;
}) {
  const { deserialize = (v) => v } = opts;

  let source = createConsumerStream<Head>(opts.from);
  if (deserialize) {
    source = source.pipeThrough(
      new TransformStream({
        transform(chunk, controller) {
          controller.enqueue(deserialize(chunk));
        },
      }),
    );
  }
  let headDeferred: null | Deferred<THead> = createDeferred();

  const streamManager = createStreamsManager({
    abortController: opts.abortController,
    onSettled: opts.onSettled ?? null,
  });

  function decodeChunkDefinition(value: ChunkDefinition, headKey: string) {
    const [_path, type, chunkId] = value;

    const controller = streamManager.getOrCreateUnder(chunkId, headKey);

    if (type === CHUNK_VALUE_TYPE_PROMISE) {
      const promise = run(async () => {
        using reader = controller.getReaderResource();

        const { done, value } = await reader.read();

        if (done) {
          throw new Error('Stream closed unexpectedly');
        }

        const [_chunkId, status, data] = value as PromiseChunk;
        switch (status) {
          case PROMISE_STATUS_FULFILLED:
            return decode(data, headKey);
          case PROMISE_STATUS_REJECTED:
            throw opts.formatError?.({ error: data }) ?? new AsyncError(data);
        }
      });
      // The promise is created eagerly, before anyone reads it, and may never be read.
      promise.catch(() => {
        // noop
      });
      return promise;
    }
    if (type === CHUNK_VALUE_TYPE_ASYNC_ITERABLE) {
      return run(async function* () {
        using reader = controller.getReaderResource();

        while (true) {
          const { done, value } = await reader.read();

          if (done) {
            throw new Error('Stream closed unexpectedly');
          }

          const [_chunkId, status, data] = value as IterableChunk;

          switch (status) {
            case ASYNC_ITERABLE_STATUS_YIELD:
              yield decode(data, headKey);
              break;
            case ASYNC_ITERABLE_STATUS_RETURN:
              return decode(data, headKey);
            case ASYNC_ITERABLE_STATUS_ERROR:
              throw opts.formatError?.({ error: data }) ?? new AsyncError(data);
          }
        }
      });
    }

    assertNever(type);
  }

  function decode(value: EncodedValue, headKey: string): unknown {
    const [[data], ...asyncProps] = value;

    for (const value of asyncProps) {
      const [key] = value;
      const decoded = decodeChunkDefinition(value, headKey);

      if (key === null) {
        return decoded;
      }

      (data as any)[key] = decoded;
    }
    return data;
  }

  const handleClose = () => {
    // If the stream closes before emitting any head data,
    // we need to reject the headDeferred to prevent hanging
    if (headDeferred) {
      headDeferred.reject(new Error('Stream closed before head was received'));
      headDeferred = null;
    }
    // Close stream controllers (not error them)
    // to preserve any buffered chunks
    streamManager.closeAll();
  };

  const handleAbort = (reason?: unknown) => {
    headDeferred?.reject(reason);
    headDeferred = null;
    streamManager.cancelAll(reason);
  };

  source
    .pipeTo(
      new WritableStream({
        write(chunkOrHead) {
          if (headDeferred) {
            const head = chunkOrHead as Record<number | string, unknown>;

            for (const [key, value] of Object.entries(chunkOrHead)) {
              const parsed = decode(value as any, key);
              head[key] = parsed;
              // A plain entry has no chunk to close, so it settles now
              streamManager.settleIfIdle(key);
            }
            headDeferred.resolve(head as THead);
            headDeferred = null;

            return;
          }
          const chunk = chunkOrHead as ChunkData;
          const [idx] = chunk;

          const controller = streamManager.getOrCreate(idx);
          controller.enqueue(chunk);
        },
        close: handleClose,
        abort: handleAbort,
      }),
    )
    .catch((error) => {
      opts.onError?.({ error });
      handleAbort(error);
    });

  return [await headDeferred.promise] as const;
}
