import { ChatMessage, ChatOptions, ProviderResponse } from '../../../types/chat';
import { Tool } from '../../../types/tool';

export interface OpenRouterProviderConfig {
  apiKey: string;
  model?: string;
  baseUrl?: string;
  httpReferer?: string;
  xTitle?: string;
}

export interface OpenRouterChatRequestBody {
  messages: OpenRouterMessage[];
  model?: string;
  prompt?: string;
  response_format?: { type: 'json_object' };
  stop?: string | string[];
  stream?: boolean;
  max_tokens?: number;
  temperature?: number;
  top_p?: number;
  top_k?: number;
  frequency_penalty?: number;
  presence_penalty?: number;
  repetition_penalty?: number;
  seed?: number;
  tools?: OpenRouterTool[];
  tool_choice?: OpenRouterToolChoice;
  logit_bias?: { [key: number]: number };
  transforms?: string[];
  models?: string[];
  route?: 'fallback';
  provider?: ProviderPreferences;
}

export type OpenRouterMessageContent = string | OpenRouterContentPart[];

export interface OpenRouterMessage {
  role: 'user' | 'assistant' | 'system' | 'tool';
  content: OpenRouterMessageContent;
  name?: string;
  tool_calls?: OpenRouterToolCall[];
}

export interface OpenRouterToolCall {
    id?: string;
    type: 'function';
    function: {
        name: string;
        arguments: string;
    };
}

export type OpenRouterContentPart = 
  | { type: 'text'; text: string }
  | { type: 'image_url'; image_url: { url: string; detail?: string } };

export interface OpenRouterTool {
  type: 'function';
  function: {
    description?: string;
    name: string;
    parameters: object;
  };
}

export type OpenRouterToolChoice = 
  | 'none'
  | 'auto'
  | { type: 'function'; function: { name: string } };

export interface OpenRouterDelta {
  role?: string;
  content?: string;
  tool_calls?: OpenRouterToolCall[];
}

export interface OpenRouterChatResponse {
  id: string;
  object: string;
  created: number;
  model: string;
  choices: {
    index: number;
    message?: {
      role: string;
      content: string;
      tool_calls?: OpenRouterToolCall[];
    };
    delta?: OpenRouterDelta;
    finish_reason: string | null;
  }[];
  usage?: {
    prompt_tokens: number;
    completion_tokens: number;
    total_tokens: number;
  };
}

export interface ProviderPreferences {
  require_parameters?: boolean;
}

export type OpenRouterCacheKey = {
  messages: ChatMessage[];
  options: ChatOptions;
  tools?: Tool[];
};