/**
 * Equity AI Tools
 *
 * equityGetProfile / equityGetFinancials / equityGetRatios / equityGetEstimates /
 * equityGetEarningsCalendar / equityGetInsiderTrading / equityDiscover:
 *   透传到 OpenBB equity API，为 AI 提供基本面和市场发现能力。
 */

import { tool } from 'ai'
import { z } from 'zod'
import type { EquityClientLike } from '@/domain/market-data/client/types'

export function createEquityTools(equityClient: EquityClientLike) {
  return {
    equityGetProfile: tool({
      description: `Get company profile and key valuation metrics for a stock.

Returns company overview (name, sector, industry, description, website, CEO, employees)
combined with key metrics (market cap, PE ratio, PB ratio, EV/EBITDA, dividend yield, etc.).

If unsure about the symbol, use marketSearchForResearch to find it.`,
      inputSchema: z.object({
        symbol: z.string().describe('Ticker symbol, e.g. "AAPL", "MSFT"'),
      }).meta({ examples: [{ symbol: 'AAPL' }] }),
      execute: async ({ symbol }) => {
        const [profile, metrics] = await Promise.all([
          equityClient.getProfile({ symbol, provider: 'yfinance' }).catch(() => []),
          equityClient.getKeyMetrics({ symbol, limit: 1, provider: 'yfinance' }).catch(() => []),
        ])
        return { profile: profile[0] ?? null, metrics: metrics[0] ?? null }
      },
    }),

    equityGetFinancials: tool({
      description: `Get financial statements for a company.

Returns income statement, balance sheet, or cash flow statement depending on the "type" parameter.
Each entry is one fiscal period (quarterly or annual).

If unsure about the symbol, use marketSearchForResearch to find it.`,
      inputSchema: z.object({
        symbol: z.string().describe('Ticker symbol, e.g. "AAPL"'),
        type: z.enum(['income', 'balance', 'cash']).describe('Statement type: "income" for income statement, "balance" for balance sheet, "cash" for cash flow'),
        period: z.enum(['annual', 'quarter']).optional().describe('Fiscal period (default: annual)'),
        limit: z.number().int().positive().optional().describe('Number of periods to return (default: 5)'),
      }).meta({ examples: [{ symbol: 'AAPL', type: 'income', period: 'annual', limit: 5 }] }),
      execute: async ({ symbol, type, period, limit }) => {
        const params: Record<string, unknown> = { symbol, provider: 'yfinance' }
        if (period) params.period = period
        if (limit) params.limit = limit

        switch (type) {
          case 'income':
            return await equityClient.getIncomeStatement(params)
          case 'balance':
            return await equityClient.getBalanceSheet(params)
          case 'cash':
            return await equityClient.getCashFlow(params)
        }
      },
    }),

    equityGetRatios: tool({
      description: `Get financial ratios for a company.

Returns profitability ratios (ROE, ROA, gross/net/operating margin),
liquidity ratios (current ratio, quick ratio), leverage ratios (debt/equity,
debt/assets), valuation (P/E, P/B, P/S, dividend yield), and more (a curated
set with clean names, plus any extra ratios the provider returns passed
through under their raw names).

By default returns the trailing-twelve-month (TTM) snapshot PLUS \`limit\`
historical periods. Use \`ttm\` to change that: "include" (default, TTM + the
historical series), "exclude" (historical series only, no TTM), "only" (just
the single TTM snapshot — \`period\`/\`limit\` are ignored in this mode).

If unsure about the symbol, use marketSearchForResearch to find it.`,
      inputSchema: z.object({
        symbol: z.string().describe('Ticker symbol, e.g. "AAPL"'),
        period: z.enum(['annual', 'quarter']).optional().describe('Fiscal period for the historical series (default: annual)'),
        limit: z.number().int().positive().optional().describe('Number of historical periods to return (default: 5; ignored when ttm="only")'),
        ttm: z.enum(['include', 'exclude', 'only']).optional().describe('TTM handling: "include" (default — TTM + history), "exclude" (history only), "only" (TTM snapshot only)'),
      }).meta({ examples: [{ symbol: 'AAPL', period: 'annual', limit: 5 }] }),
      execute: async ({ symbol, period, limit, ttm }) => {
        // The FMP fetcher defaults ttm to "only" (a single TTM row, with
        // period/limit dead). Default to "include" here so the historical
        // series — and therefore period/limit — actually come through.
        const params: Record<string, unknown> = { symbol, provider: 'fmp', ttm: ttm ?? 'include' }
        if (period) params.period = period
        if (limit) params.limit = limit
        return await equityClient.getFinancialRatios(params)
      },
    }),

    equityGetEarningsCalendar: tool({
      description: `Get upcoming and recent earnings release dates.

Returns a list of companies with their expected earnings dates.
IMPORTANT: Check this before holding positions — earnings events carry significant risk.

Can be queried by symbol (specific company) or by date range (market-wide).`,
      inputSchema: z.object({
        symbol: z.string().optional().describe('Ticker symbol to check (omit for market-wide calendar)'),
        start_date: z.string().optional().describe('Start date in YYYY-MM-DD format'),
        end_date: z.string().optional().describe('End date in YYYY-MM-DD format'),
      }).meta({ examples: [{ symbol: 'AAPL' }] }),
      execute: async ({ symbol, start_date, end_date }) => {
        const params: Record<string, unknown> = { provider: 'fmp' }
        if (symbol) params.symbol = symbol
        if (start_date) params.start_date = start_date
        if (end_date) params.end_date = end_date
        return await equityClient.getCalendarEarnings(params)
      },
    }),

    equityGetInsiderTrading: tool({
      description: `Get insider trading activity for a company.

Returns recent buy/sell transactions by company executives, directors, and major shareholders.
Insider buying is often a strong bullish signal; large insider selling may warrant caution.

If unsure about the symbol, use marketSearchForResearch to find it.`,
      inputSchema: z.object({
        symbol: z.string().describe('Ticker symbol, e.g. "AAPL"'),
        limit: z.number().int().positive().optional().describe('Number of transactions to return (default: 20)'),
      }).meta({ examples: [{ symbol: 'AAPL', limit: 20 }] }),
      execute: async ({ symbol, limit }) => {
        const params: Record<string, unknown> = { symbol, provider: 'fmp' }
        if (limit) params.limit = limit
        return await equityClient.getInsiderTrading(params)
      },
    }),

    equityDiscover: tool({
      description: `Discover trending stocks in the market right now.

Returns top gainers, losers, or most actively traded stocks.
Use this to get a pulse on what the market is trading today.`,
      inputSchema: z.object({
        type: z.enum(['gainers', 'losers', 'active']).describe('"gainers" for top price gainers, "losers" for top losers, "active" for most actively traded by volume'),
      }).meta({ examples: [{ type: 'gainers' }] }),
      execute: async ({ type }) => {
        switch (type) {
          case 'gainers':
            return await equityClient.getGainers()
          case 'losers':
            return await equityClient.getLosers()
          case 'active':
            return await equityClient.getActive()
        }
      },
    }),
  }
}
