import { z } from 'zod';
import type { ToolRegistry } from '../server.js';
import type { AdAccount, Pixel, MetaPaginatedResponse } from '../types/meta-api.js';

/**
 * Register account and discovery tools
 */
export function registerAccountTools(registry: ToolRegistry): void {
  const client = registry.getClient();

  // List ad accounts
  registry.registerTool({
    name: 'list_ad_accounts',
    description: 'List all ad accounts for the authenticated user',
    inputSchema: z.object({}),
    annotations: {
      title: 'List Ad Accounts',
      readOnlyHint: true,
      destructiveHint: false,
      idempotentHint: true,
      openWorldHint: false,
    },
    _meta: {
      labels: {
        category: "accounts",
        access: "read",
        complexity: "simple"
      }
    },
    handler: async () => {
      try {
        const response = await client.get<MetaPaginatedResponse<AdAccount>>('me/adaccounts', {
          fields: 'id,name,account_id,account_status,currency,timezone_name,timezone_offset_hours_utc,balance,amount_spent,spend_cap,age,created_time,owner,capabilities',
        });

        return {
          content: [{
            type: 'text',
            text: JSON.stringify(response.data, null, 2),
          }],
        };
      } catch (error) {
        return {
          content: [{
            type: 'text',
            text: `Error: ${error instanceof Error ? error.message : String(error)}`,
          }],
          isError: true,
        };
      }
    },
  });

  // Get account info
  registry.registerTool({
    name: 'get_account_info',
    description: 'Get detailed information about a specific ad account including currency, timezone, spend cap, and status',
    inputSchema: z.object({
      account_id: z.string().describe('Ad account ID (format: act_XXXXX)'),
    }),
    annotations: {
      title: 'Get Account Info',
      readOnlyHint: true,
      destructiveHint: false,
      idempotentHint: true,
      openWorldHint: false,
    },
    _meta: {
      labels: {
        category: "accounts",
        access: "read",
        complexity: "simple"
      }
    },
    handler: async (args) => {
      try {
        const { account_id } = args as { account_id: string };
        
        const account = await client.get<AdAccount>(account_id, {
          fields: 'id,name,account_id,account_status,currency,timezone_name,timezone_offset_hours_utc,business,balance,amount_spent,spend_cap,age,created_time,owner,funding_source,capabilities',
        });

        return {
          content: [{
            type: 'text',
            text: JSON.stringify(account, null, 2),
          }],
        };
      } catch (error) {
        return {
          content: [{
            type: 'text',
            text: `Error: ${error instanceof Error ? error.message : String(error)}`,
          }],
          isError: true,
        };
      }
    },
  });

  // Get account pages
  registry.registerTool({
    name: 'get_account_pages',
    description: 'Get Facebook Pages linked to an ad account',
    inputSchema: z.object({
      account_id: z.string().describe('Ad account ID (format: act_XXXXX)'),
    }),
    annotations: {
      title: 'Get Account Pages',
      readOnlyHint: true,
      destructiveHint: false,
      idempotentHint: true,
      openWorldHint: false,
    },
    _meta: {
      labels: {
        category: "accounts",
        access: "read",
        complexity: "simple"
      }
    },
    handler: async (args) => {
      try {
        const { account_id } = args as { account_id: string };
        
        const response = await client.get<MetaPaginatedResponse<{ id: string; name: string }>>(
          `${account_id}/agencies`,
          { fields: 'id,name' }
        );

        return {
          content: [{
            type: 'text',
            text: JSON.stringify(response.data, null, 2),
          }],
        };
      } catch (error) {
        return {
          content: [{
            type: 'text',
            text: `Error: ${error instanceof Error ? error.message : String(error)}`,
          }],
          isError: true,
        };
      }
    },
  });

  // Get business info
  registry.registerTool({
    name: 'get_business_info',
    description: 'Get Business Manager details and configuration',
    inputSchema: z.object({
      business_id: z.string().describe('Business Manager ID'),
    }),
    annotations: {
      title: 'Get Business Info',
      readOnlyHint: true,
      destructiveHint: false,
      idempotentHint: true,
      openWorldHint: false,
    },
    _meta: {
      labels: {
        category: "accounts",
        access: "read",
        complexity: "simple"
      }
    },
    handler: async (args) => {
      try {
        const { business_id } = args as { business_id: string };
        
        const business = await client.get<{ id: string; name: string; created_time: string }>(
          business_id,
          { fields: 'id,name,created_time,primary_page,owned_ad_accounts' }
        );

        return {
          content: [{
            type: 'text',
            text: JSON.stringify(business, null, 2),
          }],
        };
      } catch (error) {
        return {
          content: [{
            type: 'text',
            text: `Error: ${error instanceof Error ? error.message : String(error)}`,
          }],
          isError: true,
        };
      }
    },
  });

  // Get pixel list
  registry.registerTool({
    name: 'get_pixel_list',
    description: 'List all Meta Pixel tracking pixels for an ad account',
    inputSchema: z.object({
      account_id: z.string().describe('Ad account ID (format: act_XXXXX)'),
    }),
    annotations: {
      title: 'Get Pixel List',
      readOnlyHint: true,
      destructiveHint: false,
      idempotentHint: true,
      openWorldHint: false,
    },
    _meta: {
      labels: {
        category: "accounts",
        access: "read",
        complexity: "simple"
      }
    },
    handler: async (args) => {
      try {
        const { account_id } = args as { account_id: string };
        
        const response = await client.get<MetaPaginatedResponse<Pixel>>(
          `${account_id}/adspixels`,
          { fields: 'id,name,code,creation_time,last_fired_time,is_unavailable,data_use_setting' }
        );

        return {
          content: [{
            type: 'text',
            text: JSON.stringify(response.data, null, 2),
          }],
        };
      } catch (error) {
        return {
          content: [{
            type: 'text',
            text: `Error: ${error instanceof Error ? error.message : String(error)}`,
          }],
          isError: true,
        };
      }
    },
  });
}
