import type { FormatHandler } from "./handler";
import type { RequestFormat } from "../schemas";
import { PATH_V1_CHAT_COMPLETIONS, PATH_CHAT_COMPLETIONS, PATH_V1_MESSAGES } from "../constants";

/**
 * Format registry — maps request paths and formats to their FormatHandler.
 *
 * Registered at module load time by each format's init module.
 */
class FormatRegistryImpl {
  private handlers = new Map<RequestFormat, FormatHandler>();
  private pathMap = new Map<string, RequestFormat>();

  register(handler: FormatHandler): void {
    this.handlers.set(handler.format, handler);
  }

  registerPath(path: string, format: RequestFormat): void {
    this.pathMap.set(path, format);
  }

  /** Get handler by format identifier */
  get(format: RequestFormat): FormatHandler | undefined {
    return this.handlers.get(format);
  }

  /** Get handler matching a request path */
  getByPath(path: string): FormatHandler | undefined {
    const messagesPath = path.split("?")[0] ?? "";
    const format = this.pathMap.get(messagesPath);
    return format === undefined ? undefined : this.handlers.get(format);
  }

  /** Detect format from request body content */
  detectFormat(rawBody: string | null): RequestFormat {
    if (rawBody === null) return "unknown";
    for (const handler of this.handlers.values()) {
      if (handler.detectFormat(rawBody)) return handler.format;
    }
    return "unknown";
  }
}

export const formatRegistry = new FormatRegistryImpl();

/**
 * Get the FormatHandler for a request path.
 * Returns null if no format matches the path.
 */
export function formatForPath(path: string): FormatHandler | null {
  return formatRegistry.getByPath(path) ?? null;
}

/**
 * Resolve the wire format from the request endpoint. The endpoint is
 * authoritative because Anthropic and OpenAI request bodies overlap for
 * simple message-only calls.
 */
export function requestFormatForPath(path: string): RequestFormat {
  return formatForPath(path)?.format ?? "unknown";
}

// Register known paths
formatRegistry.registerPath(PATH_V1_MESSAGES, "anthropic");
formatRegistry.registerPath(PATH_V1_CHAT_COMPLETIONS, "openai");
formatRegistry.registerPath(PATH_CHAT_COMPLETIONS, "openai");
