import { z } from "zod";
import type { ToolRegistry } from "../server.js";
import type { AdAccount, Campaign, AdCreative, InsightRow, DatePreset } from "../types/meta-api.js";

const baseStyles = `
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #1a1a2e; color: #eee; padding: 20px; }
  .container { max-width: 1200px; margin: 0 auto; }
  h1 { font-size: 28px; margin-bottom: 24px; color: #fff; }
  .overall-score-section { background: #16213e; border-radius: 12px; padding: 40px; margin-bottom: 32px; box-shadow: 0 4px 12px rgba(0,0,0,0.3); text-align: center; }
  .score-gauge { width: 200px; height: 200px; margin: 0 auto 24px; position: relative; }
  .score-circle { width: 200px; height: 200px; border-radius: 50%; background: conic-gradient(#e94560 0deg, #e94560 var(--score-deg), #0f3460 var(--score-deg), #0f3460 360deg); display: flex; align-items: center; justify-content: center; }
  .score-inner { width: 160px; height: 160px; border-radius: 50%; background: #16213e; display: flex; align-items: center; justify-content: center; flex-direction: column; }
  .score-value { font-size: 48px; font-weight: 700; color: var(--score-color); }
  .score-label { font-size: 14px; color: #999; text-transform: uppercase; letter-spacing: 1px; margin-top: 4px; }
  .score-status { font-size: 20px; font-weight: 700; color: var(--score-color); margin-bottom: 8px; }
  .score-desc { color: #999; font-size: 14px; }
  .subscores-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; }
  .subscore-card { background: #16213e; border-radius: 12px; padding: 24px; box-shadow: 0 4px 12px rgba(0,0,0,0.3); }
  .subscore-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }
  .subscore-title { font-size: 16px; font-weight: 700; color: #fff; }
  .trend-indicator { font-size: 20px; }
  .subscore-bar { height: 12px; background: #0f3460; border-radius: 6px; overflow: hidden; margin-bottom: 12px; }
  .subscore-fill { height: 100%; transition: width 0.3s; }
  .subscore-value { font-size: 24px; font-weight: 700; margin-bottom: 8px; }
  .subscore-recommendation { background: #0f3460; border-radius: 8px; padding: 12px; font-size: 13px; color: #ddd; line-height: 1.5; }
  .error { background: #16213e; padding: 40px; border-radius: 12px; text-align: center; color: #e94560; }
`;

export function registerAccountHealthApp(registry: ToolRegistry): void {
  const client = registry.getClient();
  
  registry.registerTool({
    name: "account_health",
    description: "Account Health Score - Comprehensive health assessment with sub-scores and recommendations",
    inputSchema: z.object({
      account_id: z.string().describe("Ad Account ID (format: act_XXXXX)"),
      date_preset: z.enum([
        "last_7d", "last_14d", "last_28d", "last_30d"
      ]).optional().default("last_30d").describe("Date range for analysis")
    }),
    annotations: {
      title: "Account Health Score",
      readOnlyHint: true,
      destructiveHint: false,
      idempotentHint: false,
      openWorldHint: false
    },
    handler: async (args) => {
      const params = args as { account_id: string; date_preset?: DatePreset };
      try {
        // Fetch account info
        const account = await client.get<AdAccount>(
          `/${params.account_id}`,
          { fields: "id,name,spend_cap,amount_spent,currency,age" }
        );

        // Fetch campaigns
        const campaignsResponse = await client.get<{ data: Campaign[] }>(
          `/${params.account_id}/campaigns`,
          { fields: "id,name,status,effective_status,created_time,updated_time" }
        );
        const campaigns = campaignsResponse.data;

        // Fetch creatives
        const creativesResponse = await client.get<{ data: AdCreative[] }>(
          `/${params.account_id}/adcreatives`,
          { fields: "id,name,created_time,status", limit: "500" }
        );
        const creatives = creativesResponse.data;

        // Fetch current period insights
        const currentInsights = await client.get<{ data: InsightRow[] }>(
          `/${params.account_id}/insights`,
          {
            level: "account",
            date_preset: params.date_preset || "last_30d",
            fields: "spend,impressions,frequency,actions,action_values"
          }
        );
        const currentData = currentInsights.data[0] || {};

        // Fetch previous period insights for trend comparison (for future use)
        // const previousInsights = await client.get<{ data: InsightRow[] }>(
        //   `/${params.account_id}/insights`,
        //   {
        //     level: "account",
        //     date_preset: "last_7d",
        //     fields: "spend,actions,action_values"
        //   }
        // );
        // const previousData = previousInsights.data[0] || {};

        // Calculate sub-scores

        // 1. Budget Utilization (0-100)
        const spendCap = parseFloat(account.spend_cap || "0") / 100;
        const amountSpent = parseFloat(account.amount_spent || "0") / 100;
        const budgetUtilization = spendCap > 0 ? (amountSpent / spendCap) * 100 : 0;
        const budgetScore = budgetUtilization >= 70 && budgetUtilization <= 95 ? 100 : 
                            budgetUtilization > 95 ? 70 : 
                            budgetUtilization < 50 ? 50 : 80;
        const budgetTrend = "→"; // Placeholder

        // 2. Creative Freshness (0-100)
        const now = Date.now();
        const creativesAges = creatives
          .filter((c: AdCreative) => c.status === "ACTIVE")
          .map((c: any) => (now - new Date(c.created_time).getTime()) / (1000 * 60 * 60 * 24));
        const avgCreativeAge = creativesAges.length > 0 
          ? creativesAges.reduce((a, b) => a + b, 0) / creativesAges.length 
          : 0;
        const activeCreativeCount = creatives.filter(c => c.status === "ACTIVE").length;
        const creativeFreshnessScore = avgCreativeAge < 30 ? 100 : 
                                       avgCreativeAge < 60 ? 80 : 
                                       avgCreativeAge < 90 ? 60 : 40;
        const creativeTrend = "↓"; // Placeholder

        // 3. Audience Saturation (0-100, based on frequency)
        const frequency = parseFloat(currentData.frequency || "1");
        const saturationScore = frequency < 2 ? 100 : 
                                frequency < 3 ? 80 : 
                                frequency < 4 ? 60 : 40;
        const saturationTrend = "↑"; // Placeholder

        // 4. Conversion Efficiency (0-100)
        const currentSpend = parseFloat(currentData.spend || "0");
        // const currentConversions = currentData.actions?.find(a => 
        //   a.action_type === "purchase" || a.action_type === "offsite_conversion.fb_pixel_purchase"
        // )?.value || "0";
        const currentRevenue = currentData.action_values?.find(a => 
          a.action_type === "purchase" || a.action_type === "offsite_conversion.fb_pixel_purchase"
        )?.value || "0";
        // const currentCPA = parseInt(currentConversions) > 0 ? currentSpend / parseInt(currentConversions) : 0;
        const currentROAS = currentSpend > 0 ? parseFloat(currentRevenue) / currentSpend : 0;
        
        const conversionScore = currentROAS > 3 ? 100 : 
                               currentROAS > 2 ? 90 : 
                               currentROAS > 1 ? 70 : 50;
        const conversionTrend = "→"; // Placeholder

        // 5. Account Activity (0-100)
        const activeCampaigns = campaigns.filter(c => c.status === "ACTIVE").length;
        const totalCampaigns = campaigns.length;
        const activePercent = totalCampaigns > 0 ? (activeCampaigns / totalCampaigns) * 100 : 0;
        const activityScore = activePercent > 50 ? 100 : 
                             activePercent > 30 ? 80 : 
                             activePercent > 10 ? 60 : 40;
        const activityTrend = "→"; // Placeholder

        // Calculate overall score (weighted average)
        const overallScore = Math.round(
          (budgetScore * 0.2) +
          (creativeFreshnessScore * 0.25) +
          (saturationScore * 0.2) +
          (conversionScore * 0.25) +
          (activityScore * 0.1)
        );

        const overallStatus = overallScore > 80 ? "Excellent" : 
                             overallScore > 50 ? "Good" : "Needs Attention";
        const overallColor = overallScore > 80 ? "#27ae60" : 
                            overallScore > 50 ? "#f39c12" : "#e74c3c";
        const scoreDeg = (overallScore / 100) * 360;

        // Build HTML
        const html = `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Account Health Score</title>
  <style>
    ${baseStyles}
    .score-circle { --score-deg: ${scoreDeg}deg; }
    .score-value, .score-status { --score-color: ${overallColor}; }
  </style>
</head>
<body>
  <div class="container">
    <h1>💚 Account Health Score</h1>
    
    <div class="overall-score-section">
      <div class="score-gauge">
        <div class="score-circle">
          <div class="score-inner">
            <div class="score-value">${overallScore}</div>
            <div class="score-label">Score</div>
          </div>
        </div>
      </div>
      <div class="score-status">${overallStatus}</div>
      <div class="score-desc">Account health for ${params.date_preset || "last_30d"}</div>
    </div>
    
    <div class="subscores-grid">
      <div class="subscore-card">
        <div class="subscore-header">
          <div class="subscore-title">💰 Budget Utilization</div>
          <div class="trend-indicator">${budgetTrend}</div>
        </div>
        <div class="subscore-value" style="color: ${budgetScore > 80 ? '#27ae60' : budgetScore > 50 ? '#f39c12' : '#e74c3c'};">${budgetScore}/100</div>
        <div class="subscore-bar">
          <div class="subscore-fill" style="width: ${budgetScore}%; background: ${budgetScore > 80 ? '#27ae60' : budgetScore > 50 ? '#f39c12' : '#e74c3c'};"></div>
        </div>
        <div class="subscore-recommendation">
          ${budgetUtilization > 95 ? '⚠️ Approaching budget cap. Consider increasing spend cap or optimizing spend.' :
            budgetUtilization < 50 ? '📉 Low budget utilization. Increase bids or expand targeting.' :
            '✅ Budget pacing is healthy. Spending ${budgetUtilization.toFixed(1)}% of cap.'}
        </div>
      </div>
      
      <div class="subscore-card">
        <div class="subscore-header">
          <div class="subscore-title">🎨 Creative Freshness</div>
          <div class="trend-indicator">${creativeTrend}</div>
        </div>
        <div class="subscore-value" style="color: ${creativeFreshnessScore > 80 ? '#27ae60' : creativeFreshnessScore > 50 ? '#f39c12' : '#e74c3c'};">${creativeFreshnessScore}/100</div>
        <div class="subscore-bar">
          <div class="subscore-fill" style="width: ${creativeFreshnessScore}%; background: ${creativeFreshnessScore > 80 ? '#27ae60' : creativeFreshnessScore > 50 ? '#f39c12' : '#e74c3c'};"></div>
        </div>
        <div class="subscore-recommendation">
          ${avgCreativeAge > 60 ? '⚠️ Creatives are aging. Refresh ads to avoid creative fatigue.' :
            activeCreativeCount < 3 ? '📝 Limited active creatives. Test more variations for better performance.' :
            '✅ Creative portfolio is fresh. ${activeCreativeCount} active creatives, avg age ${avgCreativeAge.toFixed(0)} days.'}
        </div>
      </div>
      
      <div class="subscore-card">
        <div class="subscore-header">
          <div class="subscore-title">👥 Audience Saturation</div>
          <div class="trend-indicator">${saturationTrend}</div>
        </div>
        <div class="subscore-value" style="color: ${saturationScore > 80 ? '#27ae60' : saturationScore > 50 ? '#f39c12' : '#e74c3c'};">${saturationScore}/100</div>
        <div class="subscore-bar">
          <div class="subscore-fill" style="width: ${saturationScore}%; background: ${saturationScore > 80 ? '#27ae60' : saturationScore > 50 ? '#f39c12' : '#e74c3c'};"></div>
        </div>
        <div class="subscore-recommendation">
          ${frequency > 3 ? '⚠️ High frequency (${frequency.toFixed(2)}). Audiences are saturated. Expand or refresh targeting.' :
            frequency > 2 ? '⚡ Moderate frequency. Monitor for saturation and consider lookalike expansion.' :
            '✅ Healthy frequency (${frequency.toFixed(2)}). Audiences are not oversaturated.'}
        </div>
      </div>
      
      <div class="subscore-card">
        <div class="subscore-header">
          <div class="subscore-title">🎯 Conversion Efficiency</div>
          <div class="trend-indicator">${conversionTrend}</div>
        </div>
        <div class="subscore-value" style="color: ${conversionScore > 80 ? '#27ae60' : conversionScore > 50 ? '#f39c12' : '#e74c3c'};">${conversionScore}/100</div>
        <div class="subscore-bar">
          <div class="subscore-fill" style="width: ${conversionScore}%; background: ${conversionScore > 80 ? '#27ae60' : conversionScore > 50 ? '#f39c12' : '#e74c3c'};"></div>
        </div>
        <div class="subscore-recommendation">
          ${currentROAS > 2 ? '🎉 Strong ROAS (${currentROAS.toFixed(2)}x). Campaign efficiency is excellent.' :
            currentROAS > 1 ? '✅ Profitable ROAS (${currentROAS.toFixed(2)}x). Continue optimizing for scale.' :
            currentROAS > 0 ? '⚠️ Low ROAS (${currentROAS.toFixed(2)}x). Review targeting, creatives, and offer.' :
            '📊 No conversion data yet. Ensure pixel is tracking properly.'}
        </div>
      </div>
      
      <div class="subscore-card">
        <div class="subscore-header">
          <div class="subscore-title">⚡ Account Activity</div>
          <div class="trend-indicator">${activityTrend}</div>
        </div>
        <div class="subscore-value" style="color: ${activityScore > 80 ? '#27ae60' : activityScore > 50 ? '#f39c12' : '#e74c3c'};">${activityScore}/100</div>
        <div class="subscore-bar">
          <div class="subscore-fill" style="width: ${activityScore}%; background: ${activityScore > 80 ? '#27ae60' : activityScore > 50 ? '#f39c12' : '#e74c3c'};"></div>
        </div>
        <div class="subscore-recommendation">
          ${activePercent > 50 ? '✅ ${activeCampaigns}/${totalCampaigns} campaigns active. Account is actively managed.' :
            activePercent > 30 ? '⚡ Moderate activity (${activeCampaigns}/${totalCampaigns} active). Consider launching new tests.' :
            '📉 Low activity. Only ${activeCampaigns}/${totalCampaigns} campaigns active. Launch more campaigns.'}
        </div>
      </div>
    </div>
  </div>
</body>
</html>`;

        const textSummary = `Account Health Score: ${overallScore}/100 (${overallStatus})\n\n` +
          `Budget Utilization: ${budgetScore}/100 (${budgetUtilization.toFixed(1)}% of cap)\n` +
          `Creative Freshness: ${creativeFreshnessScore}/100 (${activeCreativeCount} active, avg ${avgCreativeAge.toFixed(0)} days)\n` +
          `Audience Saturation: ${saturationScore}/100 (${frequency.toFixed(2)} frequency)\n` +
          `Conversion Efficiency: ${conversionScore}/100 (${currentROAS.toFixed(2)}x ROAS)\n` +
          `Account Activity: ${activityScore}/100 (${activeCampaigns}/${totalCampaigns} campaigns active)`;

        return {
          structuredContent: {
            type: "resource",
            resource: {
              uri: "meta-ads://app/account-health",
              mimeType: "text/html",
              text: html
            }
          },
          content: [{ type: "text", text: textSummary }]
        };
      } catch (error: any) {
        const errorHtml = `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>Error</title><style>${baseStyles}</style></head>
<body><div class="container"><div class="error"><h2>⚠️ Error Loading Account Health</h2><p>${error.message}</p></div></div></body>
</html>`;
        
        return {
          structuredContent: {
            type: "resource",
            resource: { uri: "meta-ads://app/account-health", mimeType: "text/html", text: errorHtml }
          },
          content: [{ type: "text", text: `Error: ${error.message}` }]
        };
      }
    }
  });
}
