import axios, { AxiosInstance } from 'axios';
import crypto from 'node:crypto';
import { AgentSdkOptions } from './types';

export class VibeWorkClient {
  public http: AxiosInstance;

  constructor(options: AgentSdkOptions) {
    const baseUrl = options.baseUrl || 'https://agent.wooo.work';

    this.http = axios.create({
      baseURL: baseUrl,
      headers: {
        'Content-Type': 'application/json',
        ...(options.apiKey ? { 'Authorization': `Bearer ${options.apiKey}` } : {}),
        ...(options.agentId ? { 'x-agent-id': options.agentId } : {}),
        ...(options.agentName ? { 'x-agent-name': options.agentName } : {}),
      }
    });

    this.http.interceptors.request.use((config) => {
      const headers = {
        ...(config.headers as Record<string, string | number | boolean | undefined> | undefined),
      };

      if (!headers['x-request-id']) {
        headers['x-request-id'] = crypto.randomUUID();
      }
      if (options.agentId && !headers['x-agent-id']) {
        headers['x-agent-id'] = options.agentId;
      }
      if (options.agentName && !headers['x-agent-name']) {
        headers['x-agent-name'] = options.agentName;
      }

      config.headers = headers as unknown as typeof config.headers;
      return config;
    });
  }

  /**
   * Outbound Negotiation Protocol
   * Proposes a task to an external agent via their MCP or A2A endpoint.
   */
  public async proposeTask(targetAgentUrl: string, proposal: unknown) {
    console.log(`[A2A Protocol] Sending proposal to ${targetAgentUrl}`);
    const response = await this.http.post(`${targetAgentUrl}/propose`, proposal);
    return response.data;
  }

  /**
   * Outbound Negotiation Protocol
   * Negotiates bounty/reward amounts dynamically with another agent.
   */
  public async negotiateBounty(targetAgentUrl: string, taskId: string, proposedReward: number) {
    console.log(`[A2A Protocol] Negotiating reward ${proposedReward} for task ${taskId} with ${targetAgentUrl}`);
    const response = await this.http.post(`${targetAgentUrl}/negotiate`, {
      taskId,
      proposedReward
    });
    return response.data;
  }
}
