import { z } from 'zod';
import type { AirtableClient } from '../clients/airtable.js';
import { BaseIdSchema, AutomationIdSchema } from '../types/index.js';

/**
 * Automations Tools
 * 
 * Tools for viewing Airtable automations.
 * Note: Airtable's API currently has limited automation support (read-only).
 */

export function getTools(client: AirtableClient) {
  return [
    // ========================================================================
    // List Automations (Note)
    // ========================================================================
    {
      name: 'airtable_list_automations',
      description:
        'Note: Airtable\'s public API does not currently support listing or managing automations directly. This tool returns information about automation capabilities.',
      inputSchema: z.object({
        baseId: BaseIdSchema.describe('The ID of the base (starts with app).'),
      }),
      execute: async (args: { baseId: string }) => {
        return {
          note: 'Airtable\'s public API does not currently provide direct automation management.',
          alternatives: [
            'Create automations through the Airtable web interface',
            'Use webhooks (airtable_create_webhook) to receive notifications and trigger external automation',
            'Use the Airtable Scripting App for custom automation logic',
          ],
          baseId: args.baseId,
          documentation: 'https://support.airtable.com/docs/getting-started-with-airtable-automations',
        };
      },
    },

    // ========================================================================
    // Get Automation Runs (Note)
    // ========================================================================
    {
      name: 'airtable_get_automation_runs',
      description:
        'Note: Viewing automation run history is only available through the Airtable web interface. This tool provides guidance on monitoring automations.',
      inputSchema: z.object({
        baseId: BaseIdSchema.describe('The ID of the base (starts with app).'),
        automationId: AutomationIdSchema.optional().describe(
          'Optional: The ID of a specific automation.'
        ),
      }),
      execute: async (args: { baseId: string; automationId?: string }) => {
        return {
          note: 'Automation run history is not accessible via API.',
          viewInAirtable: `https://airtable.com/${args.baseId}/automations`,
          guidance: {
            monitoring: 'Check automation run history in the Airtable web interface',
            debugging: 'Use the automation run log to see inputs, outputs, and errors',
            notifications:
              'Configure automation failure notifications in automation settings',
          },
          alternatives: [
            'Use webhooks to track when automations trigger record changes',
            'Add logging steps within automations (e.g., update a log table)',
          ],
        };
      },
    },

    // ========================================================================
    // Trigger Automation via Record (Workaround)
    // ========================================================================
    {
      name: 'airtable_trigger_automation_via_record',
      description:
        'Workaround: Trigger an automation indirectly by creating or updating a record that matches the automation\'s trigger conditions.',
      inputSchema: z.object({
        baseId: BaseIdSchema.describe('The ID of the base (starts with app).'),
        tableIdOrName: z
          .string()
          .describe('Table ID or name where the automation is configured.'),
        triggerField: z
          .string()
          .describe('Field name that the automation watches (e.g., Status, Trigger).'),
        triggerValue: z
          .unknown()
          .describe('Value to set that will trigger the automation.'),
        additionalFields: z
          .record(z.unknown())
          .optional()
          .describe('Additional fields to include in the record.'),
        existingRecordId: z
          .string()
          .optional()
          .describe(
            'If provided, updates an existing record instead of creating a new one.'
          ),
      }),
      execute: async (args: {
        baseId: string;
        tableIdOrName: string;
        triggerField: string;
        triggerValue: unknown;
        additionalFields?: Record<string, unknown>;
        existingRecordId?: string;
      }) => {
        const fields: Record<string, unknown> = {
          [args.triggerField]: args.triggerValue,
          ...(args.additionalFields || {}),
        };

        if (args.existingRecordId) {
          // Update existing record
          const response = await client.updateRecords(
            args.baseId as any,
            args.tableIdOrName,
            [{ id: args.existingRecordId as any, fields }]
          );
          return {
            action: 'update',
            record: response.records[0],
            message: `Updated record ${args.existingRecordId} to trigger automation`,
          };
        } else {
          // Create new record
          const response = await client.createRecords(
            args.baseId as any,
            args.tableIdOrName,
            [{ fields }]
          );
          return {
            action: 'create',
            record: response.records[0],
            message: 'Created record to trigger automation',
          };
        }
      },
    },

    // ========================================================================
    // Check Automation Status (Workaround)
    // ========================================================================
    {
      name: 'airtable_check_automation_status',
      description:
        'Workaround: Check if an automation ran by looking for expected changes in a log table or status field.',
      inputSchema: z.object({
        baseId: BaseIdSchema.describe('The ID of the base (starts with app).'),
        tableIdOrName: z
          .string()
          .describe('Table where automation results are recorded.'),
        recordId: z
          .string()
          .describe('Record ID to check for automation results.'),
        statusField: z
          .string()
          .describe('Field name that indicates automation completion (e.g., Status, Last Run).'),
      }),
      execute: async (args: {
        baseId: string;
        tableIdOrName: string;
        recordId: string;
        statusField: string;
      }) => {
        const record = await client.getRecord(
          args.baseId as any,
          args.tableIdOrName,
          args.recordId as any
        );

        const statusValue = record.fields[args.statusField];

        return {
          recordId: record.id,
          statusField: args.statusField,
          statusValue,
          lastModified: record.createdTime,
          message:
            statusValue !== undefined
              ? 'Automation status found'
              : 'No automation status recorded',
          record,
        };
      },
    },

    // ========================================================================
    // Automation Best Practices (Info)
    // ========================================================================
    {
      name: 'airtable_automation_info',
      description:
        'Get information and best practices for working with Airtable automations.',
      inputSchema: z.object({
        topic: z
          .enum(['triggers', 'actions', 'limits', 'debugging', 'alternatives'])
          .optional()
          .describe('Specific topic to get information about.'),
      }),
      execute: async (args: { topic?: string }) => {
        const info: Record<string, unknown> = {
          overview:
            'Airtable automations run server-side when trigger conditions are met.',
          commonTriggers: [
            'When record created',
            'When record updated',
            'When record matches conditions',
            'At scheduled time',
            'When webhook received',
          ],
          commonActions: [
            'Update record',
            'Create record',
            'Send email',
            'Send webhook',
            'Run script',
            'Find records',
          ],
          limits: {
            runsPerMonth: 'Varies by plan (Pro: 25,000, Business: 100,000+)',
            scriptTimeout: '30 seconds per script action',
            apiCalls: 'API calls in scripts count toward workspace limits',
          },
          debugging: {
            runHistory: 'View in Airtable web UI under Automations tab',
            testMode: 'Use "Test automation" button to verify configuration',
            logging: 'Add "Update record" actions to write to a log table',
          },
          apiAlternatives: [
            'Use webhooks + external service (e.g., Zapier, Make, n8n)',
            'Poll for changes using list_records with filterByFormula',
            'Build custom automation using MCP + this Airtable server',
          ],
        };

        if (args.topic) {
          return {
            topic: args.topic,
            details: info[args.topic] || info,
          };
        }

        return info;
      },
    },
  ];
}
