/**
 * Discovery tools - Property management and tool discovery
 * These tools are always registered and provide gateway access
 */

import { z } from 'zod';
import type { ToolModule, ToolDefinition } from './types.js';
import type { GSCClient } from '../lib/gsc-client.js';

/**
 * Meta-tool that returns available tool categories
 * Triggers lazy registration when category is requested
 */
const discoverTools: ToolDefinition = {
  name: 'discover_tools',
  description: 'Discover available Google Search Console tool categories. Use this to see what tools you can access, then request a specific category to load those tools.',
  category: 'discovery',
  annotations: {
    readOnlyHint: true,
    idempotentHint: true
  },
  inputSchema: z.object({
    category: z.enum(['analytics', 'intelligence', 'indexing', 'sitemaps', 'management'])
      .optional()
      .describe('Specific category to discover (if omitted, returns all categories)')
  }),
  handler: async (args) => {
    const categories = {
      analytics: {
        name: 'analytics',
        description: 'Performance data analysis tools',
        tools: [
          'search_analytics - Full Search Console performance data with filtering',
          'compare_periods - Compare two time periods with delta calculations',
          'top_movers - Find biggest gainers and losers between periods',
          'mobile_vs_desktop - Device-segmented performance analysis',
          'country_breakdown - Geographic performance breakdown'
        ]
      },
      intelligence: {
        name: 'intelligence',
        description: 'Advanced SEO intelligence and insights',
        tools: [
          'detect_quick_wins - Find high-impression, low-ranking opportunities',
          'keyword_cannibalization - Detect pages competing for same keywords',
          'content_decay_detection - Identify declining content performance',
          'query_clustering - Group related queries by semantic similarity'
        ]
      },
      indexing: {
        name: 'indexing',
        description: 'URL inspection and indexing management',
        tools: [
          'inspect_url - Inspect URL indexing status and issues',
          'batch_inspect_urls - Inspect multiple URLs efficiently',
          'request_indexing - Request Google to index/re-index a URL'
        ]
      },
      sitemaps: {
        name: 'sitemaps',
        description: 'Sitemap management and monitoring',
        tools: [
          'list_sitemaps - List all submitted sitemaps',
          'get_sitemap - Get detailed sitemap information',
          'submit_sitemap - Submit a new sitemap',
          'delete_sitemap - Remove a sitemap'
        ]
      },
      management: {
        name: 'management',
        description: 'Property management operations',
        tools: [
          'add_property - Add a new property to Search Console',
          'remove_property - Remove a property from Search Console'
        ]
      }
    };

    if (args.category) {
      const cat = (categories as any)[args.category];
      return {
        content: [{
          type: 'text' as const,
          text: JSON.stringify({
            category: cat.name,
            description: cat.description,
            tools: cat.tools
          }, null, 2)
        }],
        structuredContent: {
          requestedCategory: args.category,
          categoryInfo: cat
        }
      };
    }

    // Return all categories
    return {
      content: [{
        type: 'text' as const,
        text: JSON.stringify({
          message: 'Available tool categories in Google Search Console MCP server',
          categories: Object.values(categories).map(c => ({
            name: c.name,
            description: c.description,
            toolCount: c.tools.length
          })),
          usage: 'Call discover_tools with a specific category to see detailed tool list and trigger lazy loading'
        }, null, 2)
      }]
    };
  }
};

/**
 * List all Search Console properties user has access to
 */
const listProperties: ToolDefinition = {
  name: 'list_properties',
  description: 'List all Google Search Console properties (websites) you have access to. Always available.',
  category: 'discovery',
  annotations: {
    readOnlyHint: true,
    idempotentHint: true
  },
  inputSchema: z.object({}),
  _meta: {
    labels: {
      category: "discovery",
      access: "read",
      complexity: "simple"
    }
  },
  handler: async (args, gscClient: GSCClient) => {
    try {
      const sites = await gscClient.listSites();
      
      return {
        content: [{
          type: 'text',
          text: JSON.stringify({
            count: sites.length,
            properties: sites.map(site => ({
              url: site.siteUrl,
              permission: site.permissionLevel
            }))
          }, null, 2)
        }]
      };
    } catch (error: any) {
      return {
        content: [{
          type: 'text',
          text: `Error listing properties: ${error.message}`
        }],
        isError: true
      };
    }
  }
};

/**
 * Get detailed information about a specific property
 */
const getPropertyDetails: ToolDefinition = {
  name: 'get_property_details',
  description: 'Get detailed information about a specific Search Console property including verification status.',
  category: 'discovery',
  annotations: {
    readOnlyHint: true,
    idempotentHint: true
  },
  inputSchema: z.object({
    siteUrl: z.string().describe('Property URL (e.g., "https://example.com/" or "sc-domain:example.com")')
  }),
  handler: async (args, gscClient: GSCClient) => {
    try {
      const details = await gscClient.getSiteDetails(args.siteUrl);
      
      return {
        content: [{
          type: 'text',
          text: JSON.stringify(details, null, 2)
        }]
      };
    } catch (error: any) {
      return {
        content: [{
          type: 'text',
          text: `Error getting property details: ${error.message}`
        }],
        isError: true
      };
    }
  }
};

/**
 * Verify ownership status for a property
 */
const verifyOwnership: ToolDefinition = {
  name: 'verify_ownership',
  description: 'Check ownership verification status for a Search Console property.',
  category: 'discovery',
  annotations: {
    readOnlyHint: true,
    idempotentHint: true
  },
  inputSchema: z.object({
    siteUrl: z.string().describe('Property URL to check')
  }),
  _meta: {
    labels: {
      category: "discovery",
      access: "read",
      complexity: "simple"
    }
  },
  handler: async (args, gscClient: GSCClient) => {
    try {
      const details = await gscClient.getSiteDetails(args.siteUrl);
      
      return {
        content: [{
          type: 'text',
          text: JSON.stringify({
            siteUrl: details.siteUrl,
            verified: details.verified,
            permissionLevel: details.permissionLevel,
            message: details.verified 
              ? 'Property is verified and accessible'
              : 'Property verification required'
          }, null, 2)
        }]
      };
    } catch (error: any) {
      return {
        content: [{
          type: 'text',
          text: `Error verifying ownership: ${error.message}`
        }],
        isError: true
      };
    }
  }
};

export const tools: ToolDefinition[] = [
  discoverTools,
  listProperties,
  getPropertyDetails,
  verifyOwnership
];

// Export as ToolModule
export default { tools } as ToolModule;
