import { CommandSuggestion, PortfolioAction } from '../types/terminal';

export interface TerminalCommandArgumentSpec {
  key: string;
  label: string;
  description: string;
  placeholder: string;
  required: boolean;
  options?: string[];
  consumeRest?: boolean;
}

export interface TerminalCommandSpec extends CommandSuggestion {
  arguments: TerminalCommandArgumentSpec[];
  examples?: string[];
  portfolioAction?: Extract<
    PortfolioAction,
    'buy' | 'sell' | 'deposit' | 'withdraw'
  >;
}

export const TERMINAL_COMMAND_SPECS: TerminalCommandSpec[] = [
  {
    command: '/search',
    description: 'Search live security data',
    category: 'search',
    arguments: [
      {
        key: 'query',
        label: 'Query',
        description: 'Ticker or company name to search for.',
        placeholder: 'ticker-or-company',
        required: true,
        consumeRest: true,
      },
    ],
    examples: ['/search AAPL', '/search Apple'],
  },
  {
    command: '/portfolio',
    description: 'Show portfolio overview',
    category: 'portfolio',
    arguments: [],
    examples: ['/portfolio'],
  },
  {
    command: '/portfolio stats',
    description: 'Show portfolio statistics',
    category: 'portfolio',
    arguments: [],
    examples: ['/portfolio stats'],
  },
  {
    command: '/portfolio history',
    description: 'Show recent portfolio transactions',
    category: 'portfolio',
    arguments: [
      {
        key: 'limit',
        label: 'Limit',
        description: 'Optional number of transactions to return.',
        placeholder: 'limit',
        required: false,
      },
    ],
    examples: ['/portfolio history', '/portfolio history 25'],
  },
  {
    command: '/buy',
    description: 'Create a buy order',
    category: 'portfolio',
    portfolioAction: 'buy',
    arguments: [
      {
        key: 'ticker',
        label: 'Ticker',
        description: 'Security symbol to purchase.',
        placeholder: 'ticker',
        required: true,
      },
      {
        key: 'quantity',
        label: 'Quantity',
        description: 'Number of shares to buy.',
        placeholder: 'quantity',
        required: true,
      },
      {
        key: 'price',
        label: 'Price',
        description: 'Optional execution price override.',
        placeholder: 'price',
        required: false,
      },
    ],
    examples: ['/buy NVDA 10', '/buy NVDA 10 875.50'],
  },
  {
    command: '/sell',
    description: 'Create a sell order',
    category: 'portfolio',
    portfolioAction: 'sell',
    arguments: [
      {
        key: 'ticker',
        label: 'Ticker',
        description: 'Security symbol to sell.',
        placeholder: 'ticker',
        required: true,
      },
      {
        key: 'quantity',
        label: 'Quantity',
        description: 'Number of shares to sell.',
        placeholder: 'quantity',
        required: true,
      },
      {
        key: 'price',
        label: 'Price',
        description: 'Optional execution price override.',
        placeholder: 'price',
        required: false,
      },
    ],
    examples: ['/sell MSFT 5', '/sell MSFT 5 440'],
  },
  {
    command: '/cash deposit',
    description: 'Add cash to the portfolio',
    category: 'cash',
    portfolioAction: 'deposit',
    arguments: [
      {
        key: 'amount',
        label: 'Amount',
        description: 'Cash amount to deposit.',
        placeholder: 'amount',
        required: true,
      },
    ],
    examples: ['/cash deposit 1000'],
  },
  {
    command: '/cash withdraw',
    description: 'Withdraw cash from the portfolio',
    category: 'cash',
    portfolioAction: 'withdraw',
    arguments: [
      {
        key: 'amount',
        label: 'Amount',
        description: 'Cash amount to withdraw.',
        placeholder: 'amount',
        required: true,
      },
    ],
    examples: ['/cash withdraw 500'],
  },
  {
    command: '/fa',
    description: 'SEC financial statements',
    category: 'financials',
    arguments: [
      {
        key: 'ticker',
        label: 'Ticker',
        description: 'Security symbol to load filings for.',
        placeholder: 'ticker',
        required: true,
      },
      {
        key: 'period',
        label: 'Period',
        description: 'Reporting cadence.',
        placeholder: 'annual-or-quarterly',
        required: false,
        options: ['annual', 'quarterly'],
      },
    ],
    examples: ['/fa AAPL', '/fa AAPL quarterly'],
  },
  {
    command: '/bs',
    description: 'SEC balance sheet table',
    category: 'financials',
    arguments: [
      {
        key: 'ticker',
        label: 'Ticker',
        description: 'Security symbol to load filings for.',
        placeholder: 'ticker',
        required: true,
      },
      {
        key: 'period',
        label: 'Period',
        description: 'Reporting cadence.',
        placeholder: 'annual-or-quarterly',
        required: false,
        options: ['annual', 'quarterly'],
      },
      {
        key: 'start',
        label: 'Start',
        description: 'Optional reported period start token such as 2021 or 2024Q1.',
        placeholder: 'start-period',
        required: false,
      },
      {
        key: 'end',
        label: 'End',
        description: 'Optional reported period end token such as 2024 or 2025Q2.',
        placeholder: 'end-period',
        required: false,
      },
      {
        key: 'currency',
        label: 'Currency',
        description: 'Optional ISO-4217 currency filter passed as --currency CODE.',
        placeholder: '--currency EUR',
        required: false,
        consumeRest: true,
      },
    ],
    examples: ['/bs AAPL', '/bs AAPL quarterly --currency EUR', '/bs AAPL annual 2021 2024 --currency EUR'],
  },
  {
    command: '/cf',
    description: 'SEC cash flow summary',
    category: 'cashflow',
    arguments: [
      {
        key: 'ticker',
        label: 'Ticker',
        description: 'Security symbol to load filings for.',
        placeholder: 'ticker',
        required: true,
      },
      {
        key: 'period',
        label: 'Period',
        description: 'Reporting cadence.',
        placeholder: 'annual-or-quarterly',
        required: false,
        options: ['annual', 'quarterly'],
      },
      {
        key: 'start',
        label: 'Start',
        description: 'Optional reported period start token such as 2021 or 2024Q1.',
        placeholder: 'start-period',
        required: false,
      },
      {
        key: 'end',
        label: 'End',
        description: 'Optional reported period end token such as 2024 or 2025Q2.',
        placeholder: 'end-period',
        required: false,
      },
    ],
    examples: ['/cf KO', '/cf KO annual', '/cf KO annual 2021 2024'],
  },
  {
    command: '/dvd',
    description: 'SEC dividends history',
    category: 'dividends',
    arguments: [
      {
        key: 'ticker',
        label: 'Ticker',
        description: 'Security symbol to load dividends for.',
        placeholder: 'ticker',
        required: true,
      },
    ],
    examples: ['/dvd KO'],
  },
  {
    command: '/filings',
    description: 'SEC filing history',
    category: 'financials',
    arguments: [
      {
        key: 'ticker',
        label: 'Ticker',
        description: 'Security symbol to load filing history for.',
        placeholder: 'ticker',
        required: true,
      },
      {
        key: 'options',
        label: 'Options',
        description: 'Optional flags like --page, --page-size, and --query.',
        placeholder: '--page 2 --query "10-K"',
        required: false,
        consumeRest: true,
      },
    ],
    examples: [
      '/filings AAPL',
      '/filings AAPL --page 2',
      '/filings AAPL --page-size 50 --query 10-K',
    ],
  },
  {
    command: '/concepts',
    description: 'List SEC filing concepts',
    category: 'earnings',
    arguments: [
      {
        key: 'ticker',
        label: 'Ticker',
        description: 'Security symbol to load filing concepts for.',
        placeholder: 'ticker',
        required: true,
      },
      {
        key: 'period',
        label: 'Period',
        description: 'Reporting cadence.',
        placeholder: 'annual-or-quarterly',
        required: false,
        options: ['annual', 'quarterly'],
      },
    ],
    examples: ['/concepts AAPL', '/concepts AAPL quarterly'],
  },
  {
    command: '/mappings add',
    description: 'Create a custom SEC concept mapping',
    category: 'mappings',
    arguments: [
      {
        key: 'payload',
        label: 'Payload',
        description: 'JSON payload describing the custom mapping to create.',
        placeholder: 'json-payload',
        required: true,
        consumeRest: true,
      },
    ],
    examples: [
      '/mappings add {"targetField":"total_revenues","customConcept":{"taxonomy":"us-gaap","concept":"RevenueFromContractWithCustomerExcludingAssessedTax","unitFamily":"currency"},"scope":{"ticker":"AAPL"}}',
      '/mappings add {"targetField":"free_cash_flow","mappingKind":{"formula":{"expression":"$operating_cash_flow - ABS($capital_expenditure)"}},"scope":{"ticker":"AAPL"}}',
    ],
  },
  {
    command: '/mappings update',
    description: 'Update a custom SEC concept or formula mapping',
    category: 'mappings',
    arguments: [
      {
        key: 'id',
        label: 'ID',
        description: 'Mapping ID to update.',
        placeholder: 'mapping-id',
        required: true,
      },
      {
        key: 'payload',
        label: 'Payload',
        description: 'JSON payload describing the replacement mapping fields.',
        placeholder: 'json-payload',
        required: true,
        consumeRest: true,
      },
    ],
    examples: [
      '/mappings update 00000000-0000-0000-0000-000000000000 {"targetField":"total_revenues","customConcept":{"taxonomy":"us-gaap","concept":"Revenues","unitFamily":"currency"},"scope":{"ticker":"AAPL"}}',
    ],
  },
  {
    command: '/mappings delete',
    description: 'Delete a custom SEC mapping',
    category: 'mappings',
    arguments: [
      {
        key: 'id',
        label: 'ID',
        description: 'Mapping ID to delete.',
        placeholder: 'mapping-id',
        required: true,
      },
    ],
    examples: ['/mappings delete 00000000-0000-0000-0000-000000000000'],
  },
  {
    command: '/mappings',
    description: 'Assist with custom SEC concept mappings',
    category: 'mappings',
    arguments: [
      {
        key: 'ticker',
        label: 'Ticker',
        description: 'Optional security symbol to inspect filing concepts for.',
        placeholder: 'ticker',
        required: false,
      },
      {
        key: 'period',
        label: 'Period',
        description: 'Reporting cadence when a ticker is provided.',
        placeholder: 'annual-or-quarterly',
        required: false,
        options: ['annual', 'quarterly'],
      },
    ],
    examples: ['/mappings', '/mappings AAPL', '/mappings AAPL quarterly'],
  },
  {
    command: '/formula',
    description: 'Manage formula mappings with XBRL concept references',
    category: 'mappings',
    arguments: [
      {
        key: 'subcommand',
        label: 'Subcommand',
        description: 'Subcommand: create, validate, list',
        placeholder: 'subcommand',
        required: true,
        options: ['create', 'validate', 'list'],
      },
      {
        key: 'payload',
        label: 'Payload',
        description: 'JSON payload or expression to validate',
        placeholder: 'json-payload-or-expression',
        required: false,
        consumeRest: true,
      },
    ],
    examples: [
      '/formula create {"targetField":"free_cash_flow","expression":"$operating_cash_flow - ABS($capital_expenditure)","scope":{"ticker":"AAPL"}}',
      '/formula validate "#us-gaap.GrossProfit[currency] / #us-gaap.Revenues[currency] * 100"',
      '/formula list AAPL',
    ],
  },
  {
    command: '/em',
    description: 'SEC earnings history',
    category: 'earnings',
    arguments: [
      {
        key: 'ticker',
        label: 'Ticker',
        description: 'Security symbol to load earnings for.',
        placeholder: 'ticker',
        required: true,
      },
      {
        key: 'period',
        label: 'Period',
        description: 'Reporting cadence.',
        placeholder: 'annual-or-quarterly',
        required: false,
        options: ['annual', 'quarterly'],
      },
      {
        key: 'start',
        label: 'Start',
        description: 'Optional reported period start token such as 2021 or 2024Q1.',
        placeholder: 'start-period',
        required: false,
      },
      {
        key: 'end',
        label: 'End',
        description: 'Optional reported period end token such as 2024 or 2025Q2.',
        placeholder: 'end-period',
        required: false,
      },
      {
        key: 'currency',
        label: 'Currency',
        description: 'Optional ISO-4217 currency filter passed as --currency CODE.',
        placeholder: '--currency EUR',
        required: false,
        consumeRest: true,
      },
    ],
    examples: [
      '/em SAP',
      '/em SAP quarterly --currency EUR',
      '/em SAP annual 2021 2024 --currency EUR',
    ],
  },
  {
    command: '/news',
    description: 'Market news',
    category: 'news',
    arguments: [
      {
        key: 'ticker',
        label: 'Ticker',
        description: 'Optional symbol to filter news.',
        placeholder: 'ticker',
        required: false,
      },
    ],
    examples: ['/news', '/news NVDA'],
  },
  {
    command: '/analyze',
    description: 'AI analysis',
    category: 'analysis',
    arguments: [
      {
        key: 'ticker',
        label: 'Ticker',
        description: 'Security symbol to analyze.',
        placeholder: 'ticker',
        required: true,
      },
    ],
    examples: ['/analyze AAPL'],
  },
  {
    command: '/notes add',
    description: 'Open quick research note capture',
    category: 'research',
    arguments: [],
    examples: ['/notes add'],
  },
  {
    command: '/notes current',
    description: 'Capture the current terminal context as a research note',
    category: 'research',
    arguments: [],
    examples: ['/notes current'],
  },
  {
    command: '/help',
    description: 'List commands',
    category: 'system',
    arguments: [],
    examples: ['/help'],
  },
  {
    command: '/clear',
    description: 'Clear the current terminal workspace',
    category: 'system',
    arguments: [],
    examples: ['/clear'],
  },
];

export const TERMINAL_COMMAND_SUGGESTIONS: CommandSuggestion[] =
  TERMINAL_COMMAND_SPECS.map(({ command, description, category }) => ({
    command,
    description,
    category,
  }));

export const getTerminalCommandSpec = (
  command: string,
): TerminalCommandSpec | undefined =>
  TERMINAL_COMMAND_SPECS.find((spec) => spec.command === command);

export const getTerminalCommandSpecForAction = (
  action: Extract<PortfolioAction, 'buy' | 'sell' | 'deposit' | 'withdraw'>,
): TerminalCommandSpec | undefined =>
  TERMINAL_COMMAND_SPECS.find((spec) => spec.portfolioAction === action);
