/**
 * OpenRouter — OpenAI 호환 API. 별도 transform 없이 fetch Response 를 그대로 반환.
 *
 * Base: https://openrouter.ai/api/v1
 *   POST /chat/completions  — OpenAI 형식 그대로. stream:true 면 SSE.
 *   GET  /models             — 사용 가능 모델 목록.
 *
 * 인증: Authorization: Bearer <api key>
 * 권장 헤더: HTTP-Referer / X-Title — OpenRouter 가 leaderboard / 분석에 사용 (선택).
 */

import * as vscode from 'vscode';
import { StreamParams } from './types';
import { readProviderConfig } from './providerConfig';

const BASE_URL = 'https://openrouter.ai/api/v1';

export interface OpenRouterModel {
    id: string;
    name?: string;
    context_length?: number;
    pricing?: { prompt: string; completion: string };
}

export async function streamOpenRouter(
    context: vscode.ExtensionContext,
    params: StreamParams,
): Promise<Response> {
    const cfg = await readProviderConfig(context, 'openrouter');
    if (!cfg.apiKey) {
        return _errorResponse(401, 'OpenRouter API key 가 설정되지 않았습니다. Settings 패널에서 등록해주세요.');
    }
    const body = {
        model: params.model,
        messages: params.messages.map((m) => ({ role: m.role, content: m.content })),
        stream: true,
        temperature: params.temperature,
        max_tokens: params.maxTokens,
    };
    return fetch(`${BASE_URL}/chat/completions`, {
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${cfg.apiKey}`,
            'Content-Type': 'application/json',
            'Accept': 'text/event-stream',
            'HTTP-Referer': 'https://github.com/g1nation/locallm', // OpenRouter analytics
            'X-Title': 'Astra',
        },
        body: JSON.stringify(body),
        signal: params.signal,
    });
}

export async function listOpenRouterModels(context: vscode.ExtensionContext): Promise<string[]> {
    const cfg = await readProviderConfig(context, 'openrouter');
    if (!cfg.apiKey) return [];
    try {
        const res = await fetch(`${BASE_URL}/models`, {
            headers: { 'Authorization': `Bearer ${cfg.apiKey}` },
            signal: AbortSignal.timeout(10000),
        });
        if (!res.ok) return [];
        const json: any = await res.json();
        const arr = Array.isArray(json?.data) ? json.data : [];
        return arr.map((m: any) => String(m?.id ?? '')).filter(Boolean);
    } catch {
        return [];
    }
}

function _errorResponse(status: number, msg: string): Response {
    return new Response(JSON.stringify({ error: { message: msg } }), {
        status, headers: { 'Content-Type': 'application/json' },
    });
}
