import type { ToolModule, ToolDefinition, ToolResult } from './types.js';
import type { GSCClient } from '../lib/gsc-client.js';
import { ListSitemapsSchema, GetSitemapSchema, SubmitSitemapSchema, DeleteSitemapSchema } from '../schemas/sitemaps.js';

/**
 * SITEMAP TOOLS
 * Manage sitemaps in Google Search Console
 */

// ============================================================================
// LIST SITEMAPS
// ============================================================================

const listSitemaps: ToolDefinition = {
  name: 'list_sitemaps',
  description: 'List all sitemaps submitted for a property. Shows sitemap URLs, last read dates, submission status, and processing errors.',
  category: 'sitemaps',
  annotations: {
    readOnlyHint: true,
    idempotentHint: true
  },
  inputSchema: ListSitemapsSchema,
  _meta: {
    labels: {
      category: "sitemaps",
      access: "read",
      complexity: "simple"
    }
  },
  handler: async (args, gscClient: GSCClient): Promise<ToolResult> => {
    try {
      const sitemaps = await gscClient.listSitemaps(args.siteUrl);

      if (!sitemaps || sitemaps.length === 0) {
        return {
          content: [{
            type: 'text',
            text: `No sitemaps found for ${args.siteUrl}\n\nSubmit a sitemap using the submit_sitemap tool to help Google discover your content.`
          }]
        };
      }

      // Format results
      let text = `📄 **Sitemaps for ${args.siteUrl}**\n`;
      text += `Total: ${sitemaps.length}\n\n`;
      text += `---\n\n`;

      sitemaps.forEach((sitemap, idx) => {
        text += `**${idx + 1}. ${sitemap.path}**\n`;
        
        // Status indicator
        if (sitemap.errors && Number(sitemap.errors) > 0) {
          text += `   ❌ Status: ${sitemap.errors} error(s)\n`;
        } else if (sitemap.warnings && Number(sitemap.warnings) > 0) {
          text += `   ⚠️ Status: ${sitemap.warnings} warning(s)\n`;
        } else {
          text += `   ✅ Status: OK\n`;
        }

        // Submission info
        if (sitemap.lastSubmitted) {
          text += `   Submitted: ${new Date(sitemap.lastSubmitted).toLocaleDateString()}\n`;
        }

        if (sitemap.lastDownloaded) {
          text += `   Last read: ${new Date(sitemap.lastDownloaded).toLocaleDateString()}\n`;
        }

        // Content stats
        if (sitemap.isSitemapsIndex) {
          text += `   Type: Sitemap Index\n`;
        }

        if (sitemap.contents && sitemap.contents.length > 0) {
          sitemap.contents.forEach(content => {
            text += `   ${content.type}: ${content.submitted?.toLocaleString() || 0} submitted`;
            if (content.indexed !== undefined) {
              text += `, ${content.indexed?.toLocaleString() || 0} indexed`;
            }
            text += `\n`;
          });
        }

        // Show errors/warnings if present
        if (sitemap.errors && Number(sitemap.errors) > 0) {
          text += `   ⚠️ ${sitemap.errors} error(s) detected - use get_sitemap for details\n`;
        }

        if (sitemap.warnings && Number(sitemap.warnings) > 0) {
          text += `   ⚠️ ${sitemap.warnings} warning(s) detected - use get_sitemap for details\n`;
        }

        text += `\n`;
      });

      return {
        content: [{ type: 'text', text }],
        structuredContent: {
          sitemaps: sitemaps.map(s => ({
            path: s.path,
            lastSubmitted: s.lastSubmitted,
            lastDownloaded: s.lastDownloaded,
            isSitemapsIndex: s.isSitemapsIndex,
            errors: s.errors,
            warnings: s.warnings,
            contents: s.contents
          }))
        }
      };
    } catch (error) {
      return {
        content: [{
          type: 'text',
          text: `Error listing sitemaps: ${error instanceof Error ? error.message : String(error)}`
        }],
        isError: true
      };
    }
  }
};

// ============================================================================
// GET SITEMAP
// ============================================================================

const getSitemap: ToolDefinition = {
  name: 'get_sitemap',
  description: 'Get detailed information about a specific sitemap, including processing errors, warnings, and content statistics.',
  category: 'sitemaps',
  annotations: {
    readOnlyHint: true,
    idempotentHint: true
  },
  inputSchema: GetSitemapSchema,
  _meta: {
    labels: {
      category: "sitemaps",
      access: "read",
      complexity: "simple"
    }
  },
  handler: async (args, gscClient: GSCClient): Promise<ToolResult> => {
    try {
      const sitemap = await gscClient.getSitemap(args.siteUrl, args.feedpath);

      let text = `📄 **Sitemap Details: ${sitemap.path}**\n\n`;

      // Status
      if (sitemap.errors && Number(sitemap.errors) > 0) {
        text += `❌ Status: ${sitemap.errors} error(s)\n`;
      } else if (sitemap.warnings && Number(sitemap.warnings) > 0) {
        text += `⚠️ Status: ${sitemap.warnings} warning(s)\n`;
      } else {
        text += `✅ Status: OK\n`;
      }

      text += `\n`;

      // Timestamps
      if (sitemap.lastSubmitted) {
        text += `**Last Submitted:** ${new Date(sitemap.lastSubmitted).toLocaleString()}\n`;
      }

      if (sitemap.lastDownloaded) {
        text += `**Last Downloaded:** ${new Date(sitemap.lastDownloaded).toLocaleString()}\n`;
      }

      text += `\n`;

      // Type
      if (sitemap.isSitemapsIndex) {
        text += `**Type:** Sitemap Index (contains references to other sitemaps)\n\n`;
      }

      // Content statistics
      if (sitemap.contents && sitemap.contents.length > 0) {
        text += `**Content Statistics:**\n`;
        sitemap.contents.forEach(content => {
          text += `\n${content.type}:\n`;
          text += `  Submitted: ${content.submitted?.toLocaleString() || 0}\n`;
          if (content.indexed !== undefined) {
            text += `  Indexed: ${content.indexed?.toLocaleString() || 0}\n`;
            const indexRate = content.submitted && Number(content.submitted) > 0
              ? Math.round((Number(content.indexed) / Number(content.submitted)) * 100)
              : 0;
            text += `  Index rate: ${indexRate}%\n`;
          }
        });
        text += `\n`;
      }

      // Errors and warnings
      if (sitemap.errors && Number(sitemap.errors) > 0) {
        text += `**⚠️ Errors:** ${sitemap.errors} detected\n`;
        text += `These prevent URLs from being processed. Check the sitemap file format and accessibility.\n\n`;
      }

      if (sitemap.warnings && Number(sitemap.warnings) > 0) {
        text += `**⚠️ Warnings:** ${sitemap.warnings} detected\n`;
        text += `These may impact some URLs but don't prevent sitemap processing.\n\n`;
      }

      return {
        content: [{ type: 'text', text }],
        structuredContent: sitemap
      };
    } catch (error) {
      return {
        content: [{
          type: 'text',
          text: `Error getting sitemap: ${error instanceof Error ? error.message : String(error)}`
        }],
        isError: true
      };
    }
  }
};

// ============================================================================
// SUBMIT SITEMAP
// ============================================================================

const submitSitemap: ToolDefinition = {
  name: 'submit_sitemap',
  description: 'Submit a sitemap to Google Search Console. The sitemap must be accessible at the specified URL and follow the sitemap protocol.',
  category: 'sitemaps',
  annotations: {
    readOnlyHint: false,
    idempotentHint: true
  },
  inputSchema: SubmitSitemapSchema,
  _meta: {
    labels: {
      category: "sitemaps",
      access: "write",
      complexity: "simple"
    }
  },
  handler: async (args, gscClient: GSCClient): Promise<ToolResult> => {
    try {
      await gscClient.submitSitemap(args.siteUrl, args.feedpath);

      let text = `✅ **Sitemap Submitted Successfully**\n\n`;
      text += `Property: ${args.siteUrl}\n`;
      text += `Sitemap: ${args.feedpath}\n\n`;
      text += `**Next steps:**\n`;
      text += `1. Google will fetch and process the sitemap (usually within a few hours)\n`;
      text += `2. Check processing status with list_sitemaps or get_sitemap\n`;
      text += `3. Monitor for errors or warnings in the sitemap processing\n\n`;
      text += `**Important:**\n`;
      text += `• The sitemap must be accessible without authentication\n`;
      text += `• It must follow the sitemap protocol (https://www.sitemaps.org/)\n`;
      text += `• URLs in the sitemap must match the property URL\n`;

      return {
        content: [{ type: 'text', text }],
        structuredContent: {
          siteUrl: args.siteUrl,
          feedpath: args.feedpath,
          status: 'submitted',
          timestamp: new Date().toISOString()
        }
      };
    } catch (error) {
      const errorMsg = error instanceof Error ? error.message : String(error);

      return {
        content: [{
          type: 'text',
          text: `❌ Error submitting sitemap: ${errorMsg}\n\n**Common issues:**\n• Sitemap URL is not accessible\n• Sitemap is not in the correct format\n• Sitemap URL doesn't match the property\n• You don't have permission for this property`
        }],
        isError: true
      };
    }
  }
};

// ============================================================================
// DELETE SITEMAP
// ============================================================================

const deleteSitemap: ToolDefinition = {
  name: 'delete_sitemap',
  description: 'Delete a sitemap from Google Search Console. This does NOT delete the sitemap file itself, only removes it from Search Console tracking.',
  category: 'sitemaps',
  annotations: {
    readOnlyHint: false,
    destructiveHint: true
  },
  inputSchema: DeleteSitemapSchema,
  _meta: {
    labels: {
      category: "sitemaps",
      access: "delete",
      complexity: "simple"
    }
  },
  handler: async (args, gscClient: GSCClient): Promise<ToolResult> => {
    try {
      await gscClient.deleteSitemap(args.siteUrl, args.feedpath);

      let text = `✅ **Sitemap Deleted**\n\n`;
      text += `Property: ${args.siteUrl}\n`;
      text += `Sitemap: ${args.feedpath}\n\n`;
      text += `The sitemap has been removed from Google Search Console tracking.\n\n`;
      text += `**Note:**\n`;
      text += `• This does NOT delete the actual sitemap file from your server\n`;
      text += `• URLs previously discovered via this sitemap will remain in Google's index\n`;
      text += `• You can re-submit the sitemap later if needed\n`;

      return {
        content: [{ type: 'text', text }],
        structuredContent: {
          siteUrl: args.siteUrl,
          feedpath: args.feedpath,
          status: 'deleted',
          timestamp: new Date().toISOString()
        }
      };
    } catch (error) {
      return {
        content: [{
          type: 'text',
          text: `Error deleting sitemap: ${error instanceof Error ? error.message : String(error)}`
        }],
        isError: true
      };
    }
  }
};

// ============================================================================
// EXPORTS
// ============================================================================

export const sitemapTools: ToolModule = {
  tools: [
    listSitemaps,
    getSitemap,
    submitSitemap,
    deleteSitemap
  ]
};
