import axios from 'axios';
import { logger } from '../utils/logger.js';
import { checkEnv } from '../utils/env.js';

export async function initAPI() {
  const env = checkEnv();
  
  const config = {
    baseUrl: env.GLM_BASE_URL || 'https://api.z.ai/api/coding/paas/v4',
    apiKey: env.ZAI_API_KEY || '',
  };

  const client = axios.create({
    baseURL: config.baseUrl,
    headers: {
      'Authorization': `Bearer ${config.apiKey}`,
      'Content-Type': 'application/json',
    },
    timeout: 300000,
  });

  // Test connection
  try {
    const response = await client.get('/models', {
      headers: {
        'Authorization': `Bearer ${config.apiKey}`,
      },
      timeout: 10000
    });
    logger.info(`✓ Connected to Z.AI API (${response.data?.data?.length || 0} models available)`);
  } catch (error) {
    logger.error('✗ Failed to connect to Z.AI API');
    throw error;
  }

  return {
    config,
    client,
  };
}

export class ZAIProvider {
  constructor(api) {
    this.api = api;
  }

  async chat(messages, options = {}) {
    const { model = 'glm-5.1', temperature = 0.7, maxTokens = 4096, stream = false } = options;

    try {
      const response = await this.api.client.post('/chat/completions', {
        model,
        messages,
        temperature,
        max_tokens: maxTokens,
        stream,
      });

      if (stream) {
        return response.data;
      }

      return response.data.choices[0].message;
    } catch (error) {
      logger.error('Z.AI API error:', error.response?.data || error.message);
      throw error;
    }
  }

  async complete(prompt, options = {}) {
    return this.chat([{ role: 'user', content: prompt }], options);
  }
}

export function createZAIProvider(api) {
  return new ZAIProvider(api);
}
