/**
 * mt4_get_account - Get MT4 account information
 *
 * @description Retrieves comprehensive account information from the connected MT4 terminal
 * including balance, equity, margin, leverage, and broker details.
 *
 * @returns Account information object with balance, equity, margin details
 *
 * @example
 * const result = await mt4_get_account({});
 * // Returns:
 * // {
 * //   balance: 10000.00,
 * //   equity: 10250.50,
 * //   margin: 500.00,
 * //   freeMargin: 9750.50,
 * //   marginLevel: 2050.10,
 * //   profit: 250.50,
 * //   currency: "USD",
 * //   leverage: 100,
 * //   name: "Demo Account",
 * //   server: "ICMarkets-Demo",
 * //   company: "IC Markets"
 * // }
 */

import { z } from 'zod';
import { getMT4Client, MT4AccountInfo } from '../services/mt4-client';

// ==========================================
// Schema Definition
// ==========================================

export const mt4GetAccountSchema = {
  name: 'mt4_get_account',
  description: 'Get MT4 account information including balance, equity, margin, and broker details',
  inputSchema: {
    type: 'object' as const,
    properties: {},
    required: [] as string[],
  },
};

// Input validation schema (no params required)
export const Mt4GetAccountInputSchema = z.object({});

export type Mt4GetAccountInput = z.infer<typeof Mt4GetAccountInputSchema>;

// ==========================================
// Tool Implementation
// ==========================================

export interface Mt4GetAccountResult {
  success: boolean;
  data?: MT4AccountInfo;
  error?: string;
}

export async function mt4_get_account(
  _params: Mt4GetAccountInput
): Promise<Mt4GetAccountResult> {
  try {
    const client = getMT4Client();

    // Check connection first
    const isConnected = await client.isConnected();
    if (!isConnected) {
      return {
        success: false,
        error: 'MT4 terminal is not connected',
      };
    }

    // Get account info
    const accountInfo = await client.getAccountInfo();

    return {
      success: true,
      data: accountInfo,
    };
  } catch (error) {
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error occurred',
    };
  }
}

// ==========================================
// MCP Tool Handler
// ==========================================

export async function handleMt4GetAccount(
  params: unknown
): Promise<{ content: Array<{ type: string; text: string }> }> {
  // Validate input
  const validatedParams = Mt4GetAccountInputSchema.parse(params);

  // Execute tool
  const result = await mt4_get_account(validatedParams);

  // Format response for MCP
  if (result.success && result.data) {
    const formattedOutput = `
MT4 Account Information
=======================
Account Name: ${result.data.name}
Server: ${result.data.server}
Broker: ${result.data.company}
Leverage: 1:${result.data.leverage}

Financial Summary
-----------------
Balance: ${result.data.balance.toFixed(2)} ${result.data.currency}
Equity: ${result.data.equity.toFixed(2)} ${result.data.currency}
Profit/Loss: ${result.data.profit >= 0 ? '+' : ''}${result.data.profit.toFixed(2)} ${result.data.currency}

Margin Details
--------------
Used Margin: ${result.data.margin.toFixed(2)} ${result.data.currency}
Free Margin: ${result.data.freeMargin.toFixed(2)} ${result.data.currency}
Margin Level: ${result.data.marginLevel !== null ? result.data.marginLevel.toFixed(2) + '%' : 'N/A'}
`.trim();

    return {
      content: [
        {
          type: 'text',
          text: formattedOutput,
        },
      ],
    };
  }

  return {
    content: [
      {
        type: 'text',
        text: `Error: ${result.error}`,
      },
    ],
  };
}
