import { OpenAIError } from '../error';
import type { RequestOptions } from '../internal/request-options';
import { hasOwn, isObj } from '../internal/utils/values';
import type { ChatCompletionTool } from '../resources/chat/completions';
import type {
  FunctionTool,
  NamespaceTool,
  ParsedContent,
  ParsedResponse,
  ParsedResponseFunctionToolCall,
  ParsedResponseOutputItem,
  Response,
  ResponseCreateParamsBase,
  ResponseCreateParamsNonStreaming,
  ResponseFormatTextJSONSchemaConfig,
  ResponseFunctionToolCall,
  ResponseInputItem,
  ResponseTextConfig,
  Tool,
} from '../resources/responses/responses';
import { isParseableResponseFormat, parseResponseFormatContent } from '../lib/parser';
import type { AutoParseableTextFormat } from '../lib/parser';

/** Response tools, a compatible chat completion tool, or no tools. */
export type ParseableToolsParams = Tool[] | ChatCompletionTool | null;

/** Response-creation parameters that may include tools recognized by parsing helpers. */
export type ResponseCreateParamsWithTools = ResponseCreateParamsBase & {
  /** Tools available to the model while producing the response. */
  tools?: ParseableToolsParams;
} & ResponseParsingInput;

/** Include tuples so inline input histories retain their order for parser inference. */
export type ResponseParsingInput = {
  input?: ResponseCreateParamsBase['input'] | [ResponseInputItem, ...ResponseInputItem[]];
};

/** Local parser settings for Responses helpers, alongside ordinary request options. */
export type ResponseParseOptions = RequestOptions & {
  /** Parse with this format without sending it to the API. Pass null to leave output text unparsed. */
  parseAs?: ResponseFormatTextJSONSchemaConfig | null | undefined;
};

/** Request fields that can select a plain-text or structured Responses API output format. */
type TextConfigParams = {
  /** Optional text output configuration, including its structured JSON format. */
  text?: ResponseTextConfig;
  input?: ResponseCreateParamsBase['input'];
};

/** Infers parsed output for each member of a possibly optional text-format union. */
type ParsedTextFormat<Format> = [Format] extends [never]
  ? null
  : Format extends AutoParseableTextFormat<infer ParsedT>
    ? ParsedT
    : Format extends ResponseFormatTextJSONSchemaConfig
      ? unknown
      : null;

type UpdatedContent<Item> = Item extends { type: 'configuration_update'; text?: infer Text }
  ? NonNullable<Text> extends { format: infer Format }
    ? ParsedTextFormat<Format>
    : never
  : never;

// Track possible later formats. For very long tuples, use the remaining union before hitting
// TypeScript's instantiation limit.
type ParsedHistory<Input, Fallback, Later = never, Seen extends 0[] = []> = [Input] extends [never]
  ? Fallback | Later
  : Input extends readonly [...infer Earlier, infer Last]
    ? Last extends { type: 'configuration_update'; text: { format: infer Format } }
      ? ParsedTextFormat<Format> | Later
      : Seen['length'] extends 256
        ? Fallback | Later | UpdatedContent<Input[number]>
        : ParsedHistory<Earlier, Fallback, Later | UpdatedContent<Last>, [...Seen, 0]>
    : Input extends readonly (infer Item)[]
      ? Fallback | Later | UpdatedContent<Item>
      : Fallback | Later;

type ParsedOverride<Format, Fallback> = Format extends undefined ? Fallback : ParsedTextFormat<Format>;

/** An explicit local parser takes precedence over the request's inferred output type. */
export type ParsedWithOptions<Options extends ResponseParseOptions, Fallback> = Options extends unknown
  ? 'parseAs' extends keyof Options
    ? ParsedOverride<Options['parseAs'], Fallback>
    : Fallback
  : never;

// A spread create request has an optional, fully widened input. It carries no specific
// update, so preserve its explicit top-level parser. A supplied history can refine it.
type ParsingHistory<Params extends TextConfigParams> = Params extends { input: infer Input }
  ? Input
  : ResponseCreateParamsBase['input'] extends Params['input']
    ? never
    : Params['input'];

/**
 * Resolves the type of `output_parsed` / `content[].parsed` for the given params.
 *
 * This must stay in sync with `isParseableResponseFormat()` and
 * `parseResponseFormatContent()`: formats built by an SDK helper carry their parsed
 * type in the brand, while a raw `{ type: 'json_schema' }` format is parsed with
 * `JSON.parse()` and so can only be described as `unknown`.
 */
export type ExtractParsedContentFromParams<Params extends TextConfigParams> = ParsedHistory<
  ParsingHistory<Params>,
  ParsedTextFormat<NonNullable<Params['text']>['format']>
>;

/** Only the discriminator is required to select the parser carried by a format object. */
export type ResponseParserTextFormat = { readonly type: string } | null;

function isTextFormat(value: unknown): value is NonNullable<ResponseParserTextFormat> {
  return isObj(value) && typeof value['type'] === 'string';
}

/** Select the last visible update to the text format, independently of reasoning updates. */
function effectiveTextFormat(
  { body }: RequestOptions,
  parseAs?: ResponseParseOptions['parseAs'],
): ResponseParserTextFormat {
  if (parseAs === null || !isObj(body)) {
    return parseAs ?? null;
  }
  const { input } = body;
  if (Array.isArray(input)) {
    for (let index = input.length - 1; index >= 0; index -= 1) {
      const item: unknown = input[index];
      if (!isObj(item) || item['type'] !== 'configuration_update') {
        continue;
      }
      const { text } = item;
      if (!isObj(text)) {
        continue;
      }
      const { format } = text;
      if (!isTextFormat(format)) {
        continue;
      }
      if (format.type === 'text' && parseAs !== undefined) {
        throw new OpenAIError('Cannot use parseAs with a plain-text format update.');
      }
      return parseAs ?? format;
    }
  }
  const { text } = body;
  const format = isObj(text) ? text['format'] : null;
  return parseAs ?? (isTextFormat(format) ? format : null);
}

/** Strip local options before sending and resolve the format against the prepared request body. */
export function resolveResponseParseOptions(params: TextConfigParams, options?: ResponseParseOptions) {
  const parseAs = options && hasOwn(options, 'parseAs') ? options.parseAs : undefined;
  // Reject a visible plain-text reset before making the request.
  if (parseAs != null) {
    effectiveTextFormat({ body: params }, parseAs);
  }
  const requestOptions = { ...options };
  delete requestOptions.parseAs;
  // Undefined means no body was serialized (e.g. a custom stream transport).
  // Null means this particular request intentionally has no text parser.
  let captured: ResponseParserTextFormat | undefined;
  requestOptions.__metadata = {
    ...options?.__metadata,
    captureResponseParser(prepared: RequestOptions) {
      const format = effectiveTextFormat(prepared, parseAs);
      const selector =
        format === null
          ? null
          : {
              type: format.type,
              $brand: '$brand' in format ? format.$brand : undefined,
              $parseRaw: '$parseRaw' in format ? format.$parseRaw : undefined,
            };
      captured = selector;
    },
  };
  return {
    getTextFormat: (prepared: RequestOptions) =>
      captured === undefined ? effectiveTextFormat(prepared, parseAs) : captured,
    requestOptions,
  };
}

/**
 * Adds parsed-output fields to a response, invoking parsers only when its request
 * includes an auto-parseable text format or strict function tool.
 */
export function maybeParseResponse<
  Params extends ResponseCreateParamsBase | null,
  ParsedT = Params extends null ? null : ExtractParsedContentFromParams<NonNullable<Params>>,
>(
  response: Response,
  params: Params,
  format = params && effectiveTextFormat({ body: params }),
): ParsedResponse<ParsedT> {
  if (!params || !hasAutoParseableInput(params, format)) {
    const parsed = {
      ...response,
      output_parsed: null,
      output: response.output.map((item) => {
        if (item.type === 'function_call') {
          return {
            ...item,
            parsed_arguments: null,
          };
        }

        if (item.type === 'message') {
          return {
            ...item,
            content: item.content.map((content) => ({
              ...content,
              parsed: null,
            })),
          };
        }
        return item;
      }),
    };

    if (needsOutputText(response, parsed)) {
      // SAFETY: The copy retains every response field and only adds parsed metadata; addOutputText accepts that original response structure.
      addOutputText(parsed as Response);
    }

    return parsed;
  }

  return parseResponse(response, params, format);
}

/**
 * Parses completed response text and strict function-tool arguments, matching
 * namespaced functions by both namespace and name.
 *
 * Incomplete responses and messages with an explicit non-final phase stay unparsed.
 * `output_parsed` returns the first successfully parsed output-text item.
 */
export function parseResponse<
  Params extends ResponseCreateParamsBase,
  ParsedT = ExtractParsedContentFromParams<Params>,
>(
  response: Response,
  params: Params,
  format = effectiveTextFormat({ body: params }),
): ParsedResponse<ParsedT> {
  const shouldParse = !response.status || response.status === 'completed';
  const output: ParsedResponseOutputItem<ParsedT>[] = response.output.map(
    (item): ParsedResponseOutputItem<ParsedT> => {
      if (item.type === 'function_call') {
        return shouldParse ? parseToolCall(params, item) : { ...item, parsed_arguments: null };
      }
      if (item.type === 'message') {
        const content: ParsedContent<ParsedT>[] = item.content.map((content) => {
          if (content.type === 'output_text') {
            return {
              ...content,
              parsed:
                shouldParse && (item.phase == null || item.phase === 'final_answer')
                  ? parseResponseFormatContent<ParsedT>(format, content.text)
                  : null,
            };
          }

          return content;
        });

        return {
          ...item,
          content,
        };
      }

      return item;
    },
  );

  const parsed: Omit<ParsedResponse<ParsedT>, 'output_parsed'> = { ...response, output };
  if (needsOutputText(response, parsed)) {
    addOutputText(parsed);
  }

  Object.defineProperty(parsed, 'output_parsed', {
    enumerable: true,
    get() {
      for (const output of parsed.output) {
        if (output.type !== 'message') {
          continue;
        }

        for (const content of output.content) {
          if (content.type === 'output_text' && content.parsed !== null) {
            return content.parsed;
          }
        }
      }

      return null;
    },
  });

  // SAFETY: The output_parsed getter was installed immediately above and returns the first parsed content or null.
  return parsed as ParsedResponse<ParsedT>;
}

/** Returns whether the request includes an auto-parseable text format or strict function tool. */
export function hasAutoParseableInput(
  params: ResponseCreateParamsWithTools,
  format = effectiveTextFormat({ body: params }),
): boolean {
  if (isParseableResponseFormat(format)) {
    return true;
  }

  return (
    Array.isArray(params.tools) &&
    params.tools.some(
      (tool) =>
        isAutoParsableTool(tool) ||
        (tool.type === 'function' && tool.strict === true) ||
        (tool.type === 'namespace' &&
          tool.tools.some(
            (nested) => nested.type === 'function' && (isAutoParsableTool(nested) || nested.strict === true),
          )),
    )
  );
}

/** Type-level details used to infer a Responses API function tool's parser and callback. */
type ToolOptions = {
  /** Model-visible function name used to match generated tool calls. */
  name: string;
  /** Parsed argument value accepted by the optional execution callback. */
  arguments: any;
  /** Optional callback metadata associated with the parsed function tool. */
  function?: ((args: any) => any) | undefined;
};

/** A Responses API function tool with an argument parser and optional executable callback. */
export type AutoParseableResponseTool<
  OptionsT extends ToolOptions,
  // oxlint-disable-next-line anti-slop/no-unknown-returns -- This public conditional type detects any callable callback without constraining its return type.
  HasFunction = OptionsT['function'] extends (...args: never[]) => unknown ? true : false,
> = FunctionTool & {
  /** Type-only marker for parsed tool arguments; this property does not exist at runtime. */
  __arguments: OptionsT['arguments']; // type-level only
  /** Type-only marker for the function name; this property does not exist at runtime. */
  __name: OptionsT['name']; // type-level only

  /** Non-enumerable SDK marker identifying a tool with an attached argument parser. */
  $brand: 'auto-parseable-tool';
  /** Optional callback available to helpers that execute parsed function tools. */
  $callback: ((args: OptionsT['arguments']) => any) | undefined;
  /** Parses the raw JSON argument string into the function's typed argument value. */
  $parseRaw(args: string): OptionsT['arguments'];
};

/** Copies a Responses API function tool and attaches non-enumerable parser and callback metadata. */
export function makeParseableResponseTool<OptionsT extends ToolOptions>(
  tool: FunctionTool,
  {
    parser,
    callback,
  }: {
    /** Converts the raw JSON argument string into the function's typed argument value. */
    parser: (content: string) => OptionsT['arguments'];
    /** Optional callback available to helpers that execute the parsed function. */
    callback: ((args: OptionsT['arguments']) => any) | undefined;
  },
): AutoParseableResponseTool<OptionsT> {
  const obj = { ...tool };

  Object.defineProperties(obj, {
    $brand: {
      value: 'auto-parseable-tool',
      enumerable: false,
    },
    $parseRaw: {
      value: parser,
      enumerable: false,
    },
    $callback: {
      value: callback,
      enumerable: false,
    },
  });

  // SAFETY: The non-enumerable parser brand and callbacks were installed on this copied tool immediately above.
  return obj as AutoParseableResponseTool<OptionsT>;
}

/** Returns whether a Responses API tool carries the SDK's argument-parser marker. */
export function isAutoParsableTool(tool: any): tool is AutoParseableResponseTool<any> {
  return tool?.['$brand'] === 'auto-parseable-tool';
}

function getInputToolByName(
  input_tools: Tool[],
  name: string,
  namespace?: string,
): FunctionTool | NamespaceTool.Function | undefined {
  for (const tool of input_tools) {
    if (namespace == null) {
      if (tool.type === 'function' && tool.name === name) {
        return tool;
      }
    } else if (tool.type === 'namespace' && tool.name === namespace) {
      return tool.tools.find(
        (nested): nested is NamespaceTool.Function => nested.type === 'function' && nested.name === name,
      );
    }
  }
  // Hosted discovery exposes a deferred top-level function under its own name.
  // A declared namespace above owns that identity, even if it has no matching function.
  if (namespace === name) {
    return input_tools.find(
      (tool): tool is FunctionTool =>
        tool.type === 'function' && tool.name === name && tool.defer_loading === true,
    );
  }
  return undefined;
}

function parseToolCall<Params extends ResponseCreateParamsBase>(
  params: Params,
  toolCall: ResponseFunctionToolCall,
): ParsedResponseFunctionToolCall {
  const inputTool = getInputToolByName(params.tools ?? [], toolCall.name, toolCall.namespace);

  // oxlint-disable-next-line anti-slop/no-known-value-widening -- Parsing replaces the initial null with an arbitrary caller-parser result, so unknown is required.
  let parsedArguments: unknown = null;
  if (isAutoParsableTool(inputTool)) {
    parsedArguments = inputTool.$parseRaw(toolCall.arguments);
  } else if (inputTool?.strict) {
    parsedArguments = parseResponseFormatContent(
      { type: 'json_schema', $parseRaw: undefined },
      toolCall.arguments,
    );
  }

  return {
    ...toolCall,
    parsed_arguments: parsedArguments,
  };
}

/** Matches a response function call to a strict or auto-parseable tool by namespace and name. */
export function shouldParseToolCall(
  params: ResponseCreateParamsNonStreaming | null | undefined,
  toolCall: ResponseFunctionToolCall,
): boolean {
  if (!params) {
    return false;
  }

  const inputTool = getInputToolByName(params.tools ?? [], toolCall.name, toolCall.namespace);
  return isAutoParsableTool(inputTool) || inputTool?.strict || false;
}

/**
 * Validates that compatible chat completion tools can be automatically parsed.
 *
 * @throws {OpenAIError} If a tool is not a function or is missing `strict: true`.
 */
export function validateInputTools(tools: ChatCompletionTool[] | undefined) {
  for (const tool of tools ?? []) {
    if (tool.type !== 'function') {
      throw new OpenAIError(
        `Currently only \`function\` tool types support auto-parsing; Received \`${tool.type}\``,
      );
    }

    if (tool.function.strict !== true) {
      throw new OpenAIError(
        `The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`,
      );
    }
  }
}

function needsOutputText(
  response: Response,
  target: { output_text?: Response['output_text'] | null },
): boolean {
  return !Object.getOwnPropertyDescriptor(response, 'output_text') || target.output_text == null;
}

/** Replaces `output_text` with the concatenated text from every response output message. */
export function addOutputText(rsp: Response): void {
  const texts: string[] = [];
  for (const output of rsp.output) {
    if (output.type !== 'message') {
      continue;
    }

    for (const content of output.content) {
      if (content.type === 'output_text') {
        texts.push(content.text);
      }
    }
  }

  rsp.output_text = texts.join('');
}
