<!doctype html>
<html>
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>StackSage Cloud Audit Report</title>
  <link rel="icon" type="image/png" sizes="32x32" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAXdJREFUWEe1lwEOwiAMRfFk6snUk6knU3/CNwxKf4GNxGzJpH205RdOaWxcUkr4nfM0vGO88vP9e95HTJ6Cf4ajW3YemfLIUATrzokAPAcc144A4kZEAaw4J4wL4QGAHGHfY1yLOtnY6wEg51j9ngP10BRpD0CtHsYQWg4WqQLGPETjP2YAvJxGwEMAXvGpyv44YQhHwAPoFlR27M3dBaAxUq3YS0MYQOUSPr1UUKKtbGzUcY9taG4vtR343ROiGRUchvEAVsWIOrHUCyK1oKI93QtKlVuV5S6E6obl6hjK2QZl6scIQA2DU5G33erUmPoxCzAL0/izABBqnvnqVfCoZRVepGCbNFgAQ1pekaitezgAeLxu2OyG0QjAgdcND48AALxuqOogVITRHkCpBRAvK6oLbk5DWI2VAhqJnvOUFPO7qYZKB6LRUBDTUqyKSjlWNWOmoDa6AsHje/eOqFJQS260EUnHkRNRL7ylVFvXcziXt2Ia/wLLJl4hm/thzQAAAABJRU5ErkJggg==">
  <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body {
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
      line-height: 1.6;
      color: #333;
      background: #f5f7fa;
      padding: 20px;
    }
    .container {
      max-width: 1200px;
      margin: 0 auto;
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.1);
      padding: 40px;
    }
    h1 {
      color: #1976d2;
      font-size: 32px;
      margin-bottom: 8px;
    }
    h2 {
      color: #424242;
      font-size: 24px;
      margin-top: 32px;
      margin-bottom: 16px;
      border-bottom: 2px solid #e0e0e0;
      padding-bottom: 8px;
    }
    h3 {
      color: #616161;
      font-size: 18px;
      margin-top: 24px;
      margin-bottom: 12px;
    }
    
    /* Executive Dashboard Cards */
    .dashboard {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 16px;
      margin: 24px 0 32px 0;
    }
    .card {
      padding: 24px;
      border-radius: 8px;
      text-align: center;
      box-shadow: 0 1px 3px rgba(0,0,0,0.12);
    }
    .card-savings {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
    }
    .card-issues {
      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      color: white;
    }
    .card-priority {
      background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
      color: white;
    }
    .card-waste {
      background: linear-gradient(135deg, #30cfd0 0%, #330867 100%);
      color: white;
    }
    .card-value {
      font-size: 36px;
      font-weight: bold;
      margin-bottom: 8px;
    }
    .card-label {
      font-size: 14px;
      opacity: 0.9;
    }
    
    /* Metadata section */
    .metadata {
      background: #f5f5f5;
      padding: 16px;
      border-radius: 6px;
      margin: 16px 0;
      font-size: 14px;
    }
    .metadata strong {
      color: #424242;
    }
    
    /* Badges */
    .badge {
      display: inline-block;
      padding: 4px 10px;
      border-radius: 12px;
      font-size: 11px;
      font-weight: 600;
      text-transform: uppercase;
      margin-left: 8px;
    }
    .badge-critical {
      background: #f44336;
      color: white;
    }
    .badge-high {
      background: #ff9800;
      color: white;
    }
    .badge-medium {
      background: #ffc107;
      color: #000;
    }
    .badge-low {
      background: #8bc34a;
      color: white;
    }
    .badge-info {
      background: #e0e0e0;
      color: #616161;
      border: 1px solid #bdbdbd;
    }
    .badge-skipped {
      background: #ffebee;
      color: #c62828;
      display: inline-block;
      width: fit-content;
      border: 1px solid #ffcdd2;
    }
    
    /* Provenance badges */
    .provenance-badge {
      display: inline-block;
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 12px;
      margin-right: 8px;
      border: 1px solid;
    }
    .badge-cloudwatch {
      background: #e3f2fd;
      border-color: #90caf9;
      color: #1565c0;
    }
    .badge-cost-explorer {
      background: #fff3e0;
      border-color: #ffcc80;
      color: #e65100;
    }
    .badge-live-pricing {
      background: #f1f8e9;
      border-color: #aed581;
      color: #33691e;
    }
    .badge-heuristic {
      background: #f5f5f5;
      border-color: #e0e0e0;
      color: #757575;
    }

    /* Scorecard statuses */
    .scorecard-status {
      display: inline-block;
      padding: 2px 8px;
      border-radius: 10px;
      font-size: 11px;
      font-weight: 700;
      text-transform: uppercase;
    }
    .scorecard-pass {
      background: #e8f5e9;
      color: #2e7d32;
      border: 1px solid #c8e6c9;
    }
    .scorecard-fail {
      background: #ffebee;
      color: #c62828;
      border: 1px solid #ffcdd2;
    }
    .scorecard-unknown {
      background: #fff8e1;
      color: #f9a825;
      border: 1px solid #ffecb3;
    }

    /* Instant tooltips (avoid browser title delay) */
    .tip {
      position: relative;
      display: inline-block;
    }
    .tip .tiptext {
      visibility: hidden;
      opacity: 0;
      position: absolute;
      z-index: 1000;
      left: 0;
      transform: none;
      bottom: 125%;
      min-width: 220px;
      max-width: 360px;
      padding: 8px 10px;
      border-radius: 6px;
      background: #424242;
      color: white;
      font-size: 12px;
      line-height: 1.4;
      text-align: left;
      white-space: normal;
      transition: opacity 0s;
      pointer-events: none;
    }
    .tip:hover .tiptext {
      visibility: visible;
      opacity: 1;
    }
    
    /* Tables */
    table {
      width: 100%;
      border-collapse: collapse;
      margin: 16px 0;
      font-size: 14px;
    }
    .table-wrapper {
      width: 100%;
      overflow-x: auto;
      overflow-y: visible;
      margin: 16px 0;
    }
    .findings-table {
      width: 100%;
      max-width: 100%;
      table-layout: fixed;
    }
    .findings-table th,
    .findings-table td {
      overflow-wrap: anywhere;
      min-width: 0;
      max-width: 0;
    }
    .findings-table th:nth-child(7),
    .findings-table td:nth-child(7) {
      width: 30%;
      max-width: 30%;
      overflow: hidden;
      vertical-align: top;
    }
    .findings-table td:nth-child(7) .codeblock {
      display: block;
      width: 100%;
      max-width: 100%;
    }
    .findings-table td:nth-child(7) details {
      max-width: 100%;
    }
    .findings-table td:nth-child(7) .codeblock code {
      white-space: pre-wrap;
      overflow-wrap: anywhere;
      word-break: break-word;
    }
    th, td {
      border: 1px solid #e0e0e0;
      padding: 12px;
      text-align: left;
    }
    th {
      background: #f5f5f5;
      font-weight: 600;
      color: #424242;
    }
    tr:hover {
      background: #fafafa;
    }
    .severity-critical {
      background-color: #ffebee;
    }
    .severity-high {
      background-color: #fff3e0;
    }
    .severity-medium {
      background-color: #fffde7;
    }
    .severity-low {
      background-color: #f1f8e9;
    }
    
    /* Charts */
    .chart-container {
      max-width: 600px;
      margin: 24px auto;
      padding: 20px;
      background: #fafafa;
      border-radius: 8px;
    }
    
    /* Collapsible sections */
    .collapsible {
      background-color: #f5f5f5;
      color: #424242;
      cursor: pointer;
      padding: 14px;
      border: none;
      text-align: left;
      width: 100%;
      font-size: 16px;
      font-weight: 600;
      border-radius: 6px;
      margin-top: 16px;
      transition: background-color 0.3s;
    }
    .collapsible:hover {
      background-color: #e0e0e0;
    }
    .collapsible:after {
      content: '\002B';
      font-weight: bold;
      float: right;
      font-size: 18px;
    }
    .collapsible.active:after {
      content: '\2212';
    }
    .content {
      max-height: 0;
      overflow: hidden;
      transition: max-height 0.3s ease-out;
      background: white;
    }
    .content.expanded {
      overflow: visible;
    }

    /* CLI code blocks + copy */
    .codeblock {
      position: relative;
      background: #0f172a;
      color: #e2e8f0;
      border-radius: 8px;
      padding: 12px 12px 12px 12px;
      margin-top: 8px;
      font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
      font-size: 12px;
      line-height: 1.5;
      border: 1px solid #1e293b;
      cursor: pointer;
      display: block;
      width: 100%;
      min-width: 0;
      max-height: 220px;
      max-width: 100%;
      overflow-x: auto;
      overflow-y: auto;
      -webkit-overflow-scrolling: touch;
    }
    .codeblock code {
      white-space: pre;
      display: block;
    }
    .copy-btn {
      position: absolute;
      top: 8px;
      right: 8px;
      background: #1e293b;
      color: #e2e8f0;
      border: 1px solid #334155;
      border-radius: 6px;
      padding: 4px 8px;
      font-size: 11px;
      font-weight: 600;
      cursor: pointer;
    }
    .copy-btn.copied {
      background: #0ea5e9;
      border-color: #0ea5e9;
      color: #fff;
    }
    
    /* Priority boxes */
    .priority-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 16px;
      margin: 24px 0;
    }
    .priority-box {
      border: 2px solid;
      padding: 20px;
      border-radius: 8px;
    }
    .priority-box.critical {
      border-color: #f44336;
      background: #ffebee;
    }
    .priority-box.high {
      border-color: #ff9800;
      background: #fff3e0;
    }
    .priority-box h3 {
      margin-top: 0;
      margin-bottom: 12px;
    }
    .priority-box ul {
      margin-left: 20px;
    }
    .priority-box li {
      margin-bottom: 8px;
    }
    
    /* Footer */
    .footer {
      margin-top: 40px;
      padding-top: 20px;
      border-top: 1px solid #e0e0e0;
      font-size: 12px;
      color: #757575;
    }

    /* Free-tier badge inline in h1 */
    .free-tier-watermark {
      display: inline-block;
      margin-left: 10px;
      padding: 3px 10px;
      background: #f44336;
      color: white;
      font-size: 13px;
      font-weight: 700;
      border-radius: 4px;
      vertical-align: middle;
      letter-spacing: 0.5px;
      text-transform: uppercase;
    }

    /* Diagonal full-page watermark */
    .page-watermark {
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%) rotate(-35deg);
      font-size: 110px;
      font-weight: 900;
      color: rgba(244, 67, 54, 0.06);
      pointer-events: none;
      z-index: 9999;
      white-space: nowrap;
      user-select: none;
    }

    /* Free-tier upgrade banner */
    .free-tier-banner {
      display: flex;
      align-items: center;
      gap: 14px;
      padding: 14px 18px;
      background: #fff3e0;
      border: 1px solid #ff9800;
      border-radius: 8px;
      margin: 16px 0;
    }
    .banner-icon {
      font-size: 26px;
      flex-shrink: 0;
    }
    .banner-text {
      flex: 1;
      font-size: 14px;
      line-height: 1.5;
    }
    .banner-text strong {
      display: block;
      margin-bottom: 4px;
      color: #e65100;
    }
    .banner-cta {
      flex-shrink: 0;
      padding: 8px 16px;
      background: #ff9800;
      color: white;
      text-decoration: none;
      border-radius: 6px;
      font-weight: 600;
      font-size: 14px;
      white-space: nowrap;
    }
    .banner-cta:hover {
      background: #f57c00;
    }
    
    @media (max-width: 768px) {
      .container {
        padding: 20px;
      }
      .dashboard {
        grid-template-columns: 1fr;
      }
      .priority-grid {
        grid-template-columns: 1fr;
      }
    }
  </style>
</head>
<body>
  {% if free_tier %}<div class="page-watermark" aria-hidden="true">FREE PLAN</div>{% endif %}
  <div class="container">
    <div style="display:flex;align-items:center;gap:16px;margin-bottom:4px;">
      <img src="https://stacksageai.com/logo.png" alt="StackSage" style="height:40px;width:auto;" onerror="this.style.display='none'">
    </div>
    <h1>Cloud Cost Audit Report{% if free_tier %} <span class="free-tier-watermark">FREE PLAN</span>{% endif %}</h1>
    
    <div class="metadata">
      <strong>Account:</strong> {{ account_id or 'unknown' }} | 
      <strong>Regions:</strong> {{ regions|join(', ') }} | 
      <strong>Generated:</strong> {{ timestamp }}
      {% if pricing_version %}| <strong>Pricing:</strong> v{{ pricing_version }}{% endif %}
    </div>
    
    <!-- Executive Dashboard -->
    <h2>Executive Dashboard</h2>
    <div class="dashboard">
      <div class="card card-savings">
        <div class="card-value">${{ estimated_monthly_savings }}</div>
        <div class="card-label">Potential Savings/Month</div>
      </div>
      
      <div class="card card-issues">
        <div class="card-value">{{ findings | length }}</div>
        <div class="card-label">Issues Found</div>
      </div>
      
      <div class="card card-priority">
        <div class="card-value">
          {{ (findings | selectattr('severity', 'equalto', 'critical') | list | length) + 
             (findings | selectattr('severity', 'equalto', 'high') | list | length) }}
        </div>
        <div class="card-label">High Priority Items</div>
      </div>
      
      <div class="card card-waste">
        <div class="card-value">
          {% if estimated_monthly_cost > 0 %}
            {{ ((estimated_monthly_savings / estimated_monthly_cost * 100) | round(0)) | int }}%
          {% else %}
            N/A
          {% endif %}
        </div>
        <div class="card-label">Potential Waste</div>
      </div>
    </div>
    
    <p style="font-size: 14px; color: #616161; margin: 16px 0;">
      <strong>Estimated Monthly Cost:</strong> ${{ estimated_monthly_cost }}
    </p>

    {% if free_tier and free_tier_banner %}
    <div class="free-tier-banner">
      <div class="banner-icon">🔒</div>
      <div class="banner-text">
        <strong>You're on the Free Plan — {{ free_tier_hidden_count }} findings hidden</strong>
        <span>
          Found {{ free_tier_total_findings }} total findings. Showing top {{ findings | length }} by estimated savings.
          Estimated waste in hidden findings: ~${{ "{:,.0f}".format(free_tier_hidden_savings_usd) }}/mo.
        </span>
        <span style="display:block;margin-top:6px;font-size:13px;color:#b45309;">
          <strong>Pro unlocks:</strong> all {{ free_tier_total_findings }} findings · full remediation plan · per-resource fix commands · security posture details
        </span>
      </div>
      <a href="https://stacksageai.com/#pricing" target="_blank" class="banner-cta">Unlock — $99/mo →</a>
    </div>
    {% endif %}
    
      {% if provenance %}
    <p style="margin: 16px 0;">
      <strong>Data Sources:</strong><br>
      {% if provenance.cloudwatch_metrics %}
        <span class="provenance-badge badge-cloudwatch" title="CloudWatch aggregates (Average CPU/RequestCount only)">
          📊 Live Metrics (CloudWatch, {{ provenance.metrics_lookback_days }}d)
        </span>
      {% else %}
        <span class="provenance-badge badge-heuristic">Heuristic Analysis</span>
      {% endif %}
      {% if historical_total %}
        <span class="provenance-badge badge-cost-explorer" title="Cost Explorer spend summary (service/region totals)">
          💰 Cost Explorer Data
        </span>
      {% endif %}
      {% if pricing_mode == 'api' %}
        <span class="provenance-badge badge-live-pricing" title="AWS Pricing API on-demand Linux rates">
          💲 Live Pricing
        </span>
      {% endif %}
      {% if provenance.cloudwatch_metrics %}
        <span class="provenance-badge badge-info" title="CloudWatch queries: attempted/used/remaining">
          CW Queries: {{ provenance.cloudwatch_queries_attempted | default('0') }}/{{ provenance.cloudwatch_queries_used | default('0') }}/{{ provenance.cloudwatch_queries_remaining | default('0') }}
        </span>
      {% endif %}
    </p>
    {% endif %}
    
    {% if historical_total %}
    <p style="font-size: 14px; color: #616161; margin: 16px 0;">
      <strong>Historical Spend ({{ historical_window.start }} → {{ historical_window.end }}):</strong> ${{ historical_total }}
    </p>
    {% endif %}

    {% if historical_top_services %}
    <h3>💰 Historical Spend Breakdown (Top)</h3>
    <div style="display: flex; gap: 16px; flex-wrap: wrap; margin: 12px 0 20px 0;">
      <div style="flex: 1; min-width: 280px;">
        <div style="font-size: 13px; color: #616161; margin-bottom: 6px;"><strong>Top Services</strong></div>
        <table>
          <thead>
            <tr>
              <th>Service</th>
              <th>Cost (USD)</th>
            </tr>
          </thead>
          <tbody>
            {% for row in historical_top_services %}
            <tr>
              <td>{{ row.service }}</td>
              <td>${{ row.cost }}</td>
            </tr>
            {% endfor %}
          </tbody>
        </table>
      </div>

      {% if historical_top_regions %}
      <div style="flex: 1; min-width: 280px;">
        <div style="font-size: 13px; color: #616161; margin-bottom: 6px;"><strong>Top Regions</strong></div>
        <table>
          <thead>
            <tr>
              <th>Region</th>
              <th>Cost (USD)</th>
            </tr>
          </thead>
          <tbody>
            {% for row in historical_top_regions %}
            <tr>
              <td>{{ row.region }}</td>
              <td>${{ row.cost }}</td>
            </tr>
            {% endfor %}
          </tbody>
        </table>
      </div>
      {% endif %}
    </div>
    {% endif %}

    {% if spend_movers %}
    <h3>📈 Spend Movers ({{ spend_movers.time_window.previous.start }} → {{ spend_movers.time_window.previous.end }} vs {{ spend_movers.time_window.current.start }} → {{ spend_movers.time_window.current.end }})</h3>
    <p style="font-size: 13px; color: #616161; margin: 6px 0 12px 0;">
      Aggregated deltas only. Threshold: ${{ spend_movers.min_delta_usd }}. Totals changed by ${{ spend_movers.total_delta }}{% if spend_movers.total_pct_change is not none %} ({{ spend_movers.total_pct_change }}%){% endif %}.
    </p>
    <div style="display: flex; gap: 16px; flex-wrap: wrap; margin: 12px 0 20px 0;">
      {% if spend_movers.top_increases_by_service %}
      <div style="flex: 1; min-width: 280px;">
        <div style="font-size: 13px; color: #616161; margin-bottom: 6px;"><strong>Top Service Increases</strong></div>
        <table>
          <thead>
            <tr>
              <th>Service</th>
              <th>Δ (USD)</th>
              <th>Change</th>
            </tr>
          </thead>
          <tbody>
            {% for row in spend_movers.top_increases_by_service %}
            <tr>
              <td>{{ row.key }}</td>
              <td style="color: #2e7d32; font-weight: 600;">${{ row.delta }}</td>
              <td>
                {% if row.pct_change is not none %}
                  {{ row.pct_change }}%
                {% elif row.new_spend %}
                  New spend
                {% elif row.stopped_spend %}
                  Stopped
                {% else %}
                  N/A
                {% endif %}
              </td>
            </tr>
            {% endfor %}
          </tbody>
        </table>
      </div>
      {% endif %}

      {% if spend_movers.top_decreases_by_service %}
      <div style="flex: 1; min-width: 280px;">
        <div style="font-size: 13px; color: #616161; margin-bottom: 6px;"><strong>Top Service Decreases</strong></div>
        <table>
          <thead>
            <tr>
              <th>Service</th>
              <th>Δ (USD)</th>
              <th>Change</th>
            </tr>
          </thead>
          <tbody>
            {% for row in spend_movers.top_decreases_by_service %}
            <tr>
              <td>{{ row.key }}</td>
              <td style="color: #c62828; font-weight: 600;">${{ row.delta }}</td>
              <td>
                {% if row.pct_change is not none %}
                  {{ row.pct_change }}%
                {% elif row.new_spend %}
                  New spend
                {% elif row.stopped_spend %}
                  Stopped
                {% else %}
                  N/A
                {% endif %}
              </td>
            </tr>
            {% endfor %}
          </tbody>
        </table>
      </div>
      {% endif %}
    </div>

    <div style="display: flex; gap: 16px; flex-wrap: wrap; margin: 12px 0 20px 0;">
      {% if spend_movers.top_increases_by_region %}
      <div style="flex: 1; min-width: 280px;">
        <div style="font-size: 13px; color: #616161; margin-bottom: 6px;"><strong>Top Region Increases</strong></div>
        <table>
          <thead>
            <tr>
              <th>Region</th>
              <th>Δ (USD)</th>
              <th>Change</th>
            </tr>
          </thead>
          <tbody>
            {% for row in spend_movers.top_increases_by_region %}
            <tr>
              <td>{{ row.key }}</td>
              <td style="color: #2e7d32; font-weight: 600;">${{ row.delta }}</td>
              <td>
                {% if row.pct_change is not none %}
                  {{ row.pct_change }}%
                {% elif row.new_spend %}
                  New spend
                {% elif row.stopped_spend %}
                  Stopped
                {% else %}
                  N/A
                {% endif %}
              </td>
            </tr>
            {% endfor %}
          </tbody>
        </table>
      </div>
      {% endif %}

      {% if spend_movers.top_decreases_by_region %}
      <div style="flex: 1; min-width: 280px;">
        <div style="font-size: 13px; color: #616161; margin-bottom: 6px;"><strong>Top Region Decreases</strong></div>
        <table>
          <thead>
            <tr>
              <th>Region</th>
              <th>Δ (USD)</th>
              <th>Change</th>
            </tr>
          </thead>
          <tbody>
            {% for row in spend_movers.top_decreases_by_region %}
            <tr>
              <td>{{ row.key }}</td>
              <td style="color: #c62828; font-weight: 600;">${{ row.delta }}</td>
              <td>
                {% if row.pct_change is not none %}
                  {{ row.pct_change }}%
                {% elif row.new_spend %}
                  New spend
                {% elif row.stopped_spend %}
                  Stopped
                {% else %}
                  N/A
                {% endif %}
              </td>
            </tr>
            {% endfor %}
          </tbody>
        </table>
      </div>
      {% endif %}
    </div>
    {% endif %}

    <!-- Executive Summary -->
    <h2>Executive Summary</h2>
    <p style="font-size: 15px; line-height: 1.8; color: #424242;">{{ executive_summary }}</p>

    {% if security_scorecard %}
    <h3>🛡️ Security Posture Scorecard</h3>
    <p style="font-size: 14px; color: #616161; margin: 8px 0;">
      A quick view of baseline security controls (pass/fail/unknown). See Security Posture Findings for details.
    </p>
    <table>
      <thead>
        <tr>
          <th>Control</th>
          <th>Status</th>
        </tr>
      </thead>
      <tbody>
        {% for item in security_scorecard %}
        <tr>
          <td>{{ item.label }}</td>
          <td>
            <span class="scorecard-status scorecard-{{ item.status }}">
              {{ item.status | upper }}
            </span>
          </td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
    {% endif %}

    {% set guardrail_types = [
      'cost_guardrail_missing_budgets',
      'cost_guardrail_missing_anomaly_detection',
      'cost_guardrail_missing_anomaly_subscriptions',
      'cost_guardrail_check_skipped'
    ] %}
    {% set cost_guardrail_findings = findings | selectattr('type', 'in', guardrail_types) | list %}
    {% if cost_guardrail_findings %}
    <h3>🧯 Cost Guardrails</h3>
    <p style="font-size: 14px; color: #616161; margin: 8px 0;">
      These checks verify that spend guardrails (Budgets and Anomaly Detection alerts) are configured.
    </p>
    <ul style="font-size: 14px; line-height: 1.8;">
      {% for f in cost_guardrail_findings %}
        <li>
          <strong>{{ f.type }}</strong> — {{ f.summary | default(f.explanation) }}
        </li>
      {% endfor %}
    </ul>
    {% endif %}
    
    <!-- Top Savings Opportunities -->
    {% if top_savings %}
    <h3>🎯 Top Savings Opportunities</h3>
    <ul style="font-size: 14px; line-height: 1.8;">
      {% for d in top_savings[:5] %}
        <li>
          <strong>{{ d.type }}</strong> ({{ d.id }}) — 
          <span style="color: #1976d2; font-weight: 600;">${{ d.estimated_monthly_savings_usd | default('N/A') }}/month</span>
          via {{ d.action | default(d.recommended_action) }}
          {% if d.current_instance_type and d.recommended_instance_type %}
            <br><small style="color: #666; margin-left: 20px;">{{ d.current_instance_type }} → {{ d.recommended_instance_type }}</small>
          {% endif %}
          {% if d.explanation %}
            <br><small style="color: #666; margin-left: 20px; font-style: italic;">{{ d.explanation }}</small>
          {% endif %}
        </li>
      {% endfor %}
    </ul>
    {% elif top_cost_items %}
    <h3>💸 Top Cost Drivers</h3>
    <p style="font-size:13px;color:#757575;margin-bottom:8px;">No direct savings estimate available — these are your highest-cost resources.</p>
    <ul style="font-size: 14px; line-height: 1.8;">
      {% for d in top_cost_items %}
        <li>
          <strong>{{ d.type }}</strong> ({{ d.id or d.resource or d.resource_id or 'unknown' }}) —
          <span style="color: #e65100; font-weight: 600;">${{ d.estimated_monthly_cost_usd }}/month</span>
          {% if d.instance_class %}<small style="color:#666;"> · {{ d.instance_class }}</small>{% endif %}
          {% if d.explanation %}
            <br><small style="color: #666; margin-left: 20px; font-style: italic;">{{ d.explanation }}</small>
          {% endif %}
        </li>
      {% endfor %}
    </ul>
    {% endif %}

    <!-- Cost Breakdown Chart -->
    {% if counts_by_type %}
    <h2>Resource Distribution</h2>
    <div class="chart-container">
      <canvas id="costChart"></canvas>
    </div>
    <script>
      const ctx = document.getElementById('costChart').getContext('2d');
      new Chart(ctx, {
        type: 'pie',
        data: {
          labels: [{% for t in counts_by_type.keys() %}'{{ t }}'{% if not loop.last %}, {% endif %}{% endfor %}],
          datasets: [{
            data: [{% for c in counts_by_type.values() %}{{ c }}{% if not loop.last %}, {% endif %}{% endfor %}],
            backgroundColor: [
              '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF',
              '#FF9F40', '#FF6384', '#C9CBCF', '#4BC0C0', '#FF9F40'
            ]
          }]
        },
        options: {
          responsive: true,
          plugins: {
            legend: {
              position: 'bottom'
            },
            title: {
              display: true,
              text: 'Resources by Type'
            }
          }
        }
      });
    </script>
    {% endif %}

    <!-- Priority Implementation Roadmap -->
    {% set critical_findings = findings | selectattr('severity', 'equalto', 'critical') | list %}
    {% set high_findings = findings | selectattr('severity', 'equalto', 'high') | list %}
    
    {% if critical_findings or high_findings %}
    <h2>📋 Implementation Roadmap</h2>
    <div class="priority-grid">
      {% if critical_findings %}
      <div class="priority-box critical">
        <h3 style="color: #c62828;">🔥 Critical Priority ({{ critical_findings | length }})</h3>
        <ul>
          {% for f in critical_findings[:5] %}
            <li>
              {{ f.recommended_action | default(f.action) }}
              {% if f.estimated_monthly_savings_usd %}
                <br><small style="color: #1565c0;">💰 Save ${{ f.estimated_monthly_savings_usd }}/month</small>
              {% endif %}
            </li>
          {% endfor %}
        </ul>
      </div>
      {% endif %}
      
      {% if high_findings %}
      <div class="priority-box high">
        <h3 style="color: #e65100;">⚡ High Priority ({{ high_findings | length }})</h3>
        <ul>
          {% for f in high_findings[:5] %}
            <li>
              {{ f.recommended_action | default(f.action) }}
              {% if f.estimated_monthly_savings_usd %}
                <br><small style="color: #1565c0;">💰 Save ${{ f.estimated_monthly_savings_usd }}/month</small>
              {% endif %}
            </li>
          {% endfor %}
        </ul>
      </div>
      {% endif %}
    </div>
    {% endif %}

    <!-- Top 5 Quick Wins / Cost Drivers -->
    {% if top_savings %}
    <h2>💡 Top 5 Quick Wins</h2>
    <table>
      <thead>
        <tr>
          <th>Type</th>
          <th>Resource</th>
          <th>Region</th>
          <th>Est. Savings (USD/mo)</th>
          <th>Recommended Action</th>
        </tr>
      </thead>
      <tbody>
      {% for f in top_savings[:5] %}
        <tr class="severity-{{ f.severity | default('low') }}">
          <td>{{ f.type }}</td>
          <td style="font-family: monospace; font-size: 12px;">{{ f.id or f.resource or f.resource_id or '' }}</td>
          <td>{{ f.region | default('') }}</td>
          <td style="font-weight: 600; color: #1976d2;">
            ${{ f.estimated_monthly_savings_usd | default('N/A') }}
          </td>
          <td>{{ f.action | default(f.recommended_action) }}</td>
        </tr>
      {% endfor %}
      </tbody>
    </table>
    {% elif top_cost_items %}
    <h2>💸 Top Cost Drivers</h2>
    <p style="font-size:13px;color:#757575;margin-bottom:8px;">No direct savings calculable — showing highest-cost resources.</p>
    <table>
      <thead>
        <tr>
          <th>Type</th>
          <th>Resource</th>
          <th>Region</th>
          <th>Monthly Cost (USD)</th>
          <th>Instance Class</th>
        </tr>
      </thead>
      <tbody>
      {% for f in top_cost_items %}
        <tr class="severity-{{ f.severity | default('low') }}">
          <td>{{ f.type }}</td>
          <td style="font-family: monospace; font-size: 12px;">{{ f.id or f.resource or f.resource_id or '' }}</td>
          <td>{{ f.region | default('') }}</td>
          <td style="font-weight: 600; color: #e65100;">
            ${{ f.estimated_monthly_cost_usd }}
          </td>
          <td>{{ f.instance_class | default('') }}</td>
        </tr>
      {% endfor %}
      </tbody>
    </table>
    {% endif %}

    <!-- Resource Counts -->
    <button class="collapsible">📊 Resource Counts by Type</button>
    <div class="content">
      <table class="findings-table" style="margin-top: 16px;">
        <colgroup>
          <col style="width: 12%;" />
          <col style="width: 16%;" />
          <col style="width: 8%;" />
          <col style="width: 8%;" />
          <col style="width: 10%;" />
          <col style="width: 10%;" />
          <col style="width: 30%;" />
          <col style="width: 6%;" />
        </colgroup>
        <thead>
          <tr>
            <th>Resource Type</th>
            <th>Count</th>
          </tr>
        </thead>
        <tbody>
        {% for t, c in counts_by_type.items() %}
          <tr>
            <td>{{ t }}</td>
            <td><strong>{{ c }}</strong></td>
          </tr>
        {% endfor %}
        </tbody>
      </table>
    </div>


    {% macro findings_table(findings_list) -%}
      <table style="margin-top: 16px;">
        <thead>
          <tr>
            <th>Type</th>
            <th>Resource</th>
            <th>Region</th>
            <th>Severity</th>
            <th>Est. Cost (USD/mo)</th>
            <th>Est. Savings (USD/mo)</th>
            <th>Recommended Action</th>
            <th>Estimation</th>
          </tr>
        </thead>
        <tbody>
        {% for f in findings_list %}
          <tr class="severity-{{ f.severity | default('low') }}">
            <td>
              {{ f.type }}
              {% if f.confidence %}
                <span class="badge badge-info" title="Detection confidence">
                  {{ '%.0f' % (f.confidence*100) }}%
                </span>
              {% endif %}
              {% if f.reason_codes is defined and 'cw_metrics_measured' in f.reason_codes %}
                <span class="badge badge-cloudwatch" title="Measured via CloudWatch aggregate metrics">
                  Measured
                </span>
              {% endif %}
              {% if f.reason_codes is defined and 'cw_no_data' in f.reason_codes %}
                <span class="tip">
                  <span class="badge badge-info">No Data</span>
                  <span class="tiptext">CloudWatch returned no datapoints for the lookback window.</span>
                </span>
              {% endif %}
              {% if f.reason_codes is defined and 'cw_not_authorized' in f.reason_codes %}
                <span class="tip">
                  <span class="badge badge-info">Access Denied</span>
                  <span class="tiptext">Missing CloudWatch permissions to read metrics for this resource.</span>
                </span>
              {% endif %}
              {% if f.metric_status == 'skipped_budget' %}
                <span class="badge badge-skipped" title="Metric query skipped due to budget exhaustion">
                  Skipped
                </span>
              {% endif %}
            </td>
            <td style="font-family: monospace; font-size: 12px;">
              {{ f.id }}
              {% if f.type == 'ec2_generation_upgrade' and f.current_instance_type %}
                <br><small style="color: #666;">{{ f.current_instance_type }} → {{ f.recommended_instance_type }}</small>
              {% endif %}
              {% if f.type == 'underutilized_rds' and f.instance_class %}
                <br><small style="color: #666;">{{ f.instance_class }}
                {% if f.recommended_instance_class %}
                  → {{ f.recommended_instance_class }}
                {% endif %}
                </small>
              {% endif %}
              {% if f.type == 'old_snapshot' and f.days_old %}
                <br><small style="color: #666;">{{ f.days_old }} days old</small>
              {% endif %}
            </td>
            <td>{{ f.region | default('') }}</td>
            <td>
              <span class="badge badge-{{ f.severity | default('low') }}">
                {{ f.severity | default('low') | upper }}
              </span>
            </td>
            <td>{{ f.estimated_monthly_cost_usd | default('N/A') }}</td>
            <td style="font-weight: 600; color: #1976d2;">
              {{ f.estimated_monthly_savings_usd | default('N/A') }}
              {% if f.savings_percentage %}
                <br><small style="color: #666;">({{ f.savings_percentage }}% savings)</small>
              {% endif %}
            </td>
            <td>
              {{ f.recommended_action | default(f.action) }}
              {% if f.type == 'underutilized_rds' %}
                {% if f.cpu_avg is defined and f.cpu_avg is not none %}
                  <br><small style="color: #666;">CPU: {{ '%.1f' % f.cpu_avg }}%</small>
                {% endif %}
                {% if f.storage_utilization_pct is defined and f.storage_utilization_pct is not none %}
                  <small style="color: #666;"> • Storage: {{ '%.1f' % f.storage_utilization_pct }}% used</small>
                {% endif %}
              {% endif %}
              {% if f.explanation %}
                <br><small style="color: #666; font-style: italic;">{{ f.explanation }}</small>
              {% endif %}
              {% if f.verification_commands %}
                <details style="margin-top: 6px;">
                  <summary style="cursor: pointer; font-size: 12px; color: #1976d2;">Verify (AWS CLI)</summary>
                  <div class="codeblock" role="button" aria-label="Copy AWS CLI commands">
                    <button class="copy-btn" type="button">Copy</button>
                    <code>{{ f.verification_commands | join('\n') | e }}</code>
                  </div>
                </details>
              {% endif %}
            </td>
            <td>
              {% set method = f.estimation_method %}
              {% set adj = f.adjusted_monthly_cost_usd %}
              {% set asm = f.assumptions %}
              {% if method or adj or asm %}
                {% set tip_parts = [] %}
                {% if method %}{% set _ = tip_parts.append('Method: ' ~ method) %}{% endif %}
                {% if adj %}{% set _ = tip_parts.append('Adjusted cost: $' ~ ('%.2f' % adj) ~ '/mo') %}{% endif %}
                {% if asm %}{% set _ = tip_parts.append('Assumptions: ' ~ asm) %}{% endif %}
                <span class="tip">
                  <span class="badge badge-info">📐 Estimation</span>
                  <span class="tiptext">{{ tip_parts | join(' • ') }}</span>
                </span>
              {% else %}
                <span class="badge badge-heuristic" title="Static pricing/heuristics">Heuristic</span>
              {% endif %}
            </td>
          </tr>
        {% endfor %}
        </tbody>
      </table>
    {%- endmacro %}

    {% if financial_findings is defined %}
    <button class="collapsible">💰 Financial Findings ({{ financial_findings | length }} total)</button>
    <div class="content">
      <div class="table-wrapper">
        {{ findings_table(financial_findings) }}
      </div>
    </div>
    {% endif %}

    {% if security_posture_findings is defined %}
    <button class="collapsible">🛡️ Security Posture Findings ({{ security_posture_findings | length }} total)</button>
    <div class="content">
      <div class="table-wrapper">
        {{ findings_table(security_posture_findings) }}
      </div>
    </div>
    {% endif %}

    {% if skipped_findings is defined and skipped_findings %}
    <button class="collapsible">⏭ Checks Skipped ({{ skipped_findings | length }} total)</button>
    <div class="content">
      <div class="table-wrapper">
        {{ findings_table(skipped_findings) }}
      </div>
    </div>
    {% endif %}

    <!-- All Findings (Collapsible) -->
    <button class="collapsible">🔍 All Findings ({{ findings | length }} total)</button>
    <div class="content">
      <div class="table-wrapper">
        {{ findings_table(findings) }}
      </div>
    </div>

    <p style="margin-top: 24px; font-size: 13px; color: #757575;">
      <em>📁 CSV export available:</em> findings.csv generated alongside this report.
    </p>

    <!-- Footer -->
    <div class="footer">
      <p>
        <strong>Privacy Note:</strong> StackSage uses aggregate CloudWatch metrics (e.g., Average CPUUtilization, RequestCount), 
        Cost Explorer totals, and public Pricing metadata. No object contents, application payloads, or sensitive data are accessed. 
        S3 lifecycle savings are heuristic estimates without accessing object sizes.
      </p>
      <p style="margin-top: 12px;">
        Generated by <strong>StackSage</strong> • Report any issues to hello@stacksage.io
      </p>
    </div>

    <!-- Collapsible sections script -->
    <script>
      document.querySelectorAll('.collapsible').forEach(btn => {
        btn.addEventListener('click', function() {
          this.classList.toggle('active');
          const content = this.nextElementSibling;
          if (content.style.maxHeight) {
            content.style.maxHeight = null;
            content.classList.remove('expanded');
          } else {
            content.classList.add('expanded');
            content.style.maxHeight = content.scrollHeight + 'px';
          }
        });
      });

      document.querySelectorAll('.codeblock').forEach(block => {
        const button = block.querySelector('.copy-btn');
        const code = block.querySelector('code');
        const copy = () => {
          const text = code.innerText;
          navigator.clipboard.writeText(text).then(() => {
            button.classList.add('copied');
            button.textContent = 'Copied';
            setTimeout(() => {
              button.classList.remove('copied');
              button.textContent = 'Copy';
            }, 1500);
          }).catch(() => {
            button.textContent = 'Select';
          });
        };
        button.addEventListener('click', (e) => {
          e.stopPropagation();
          copy();
        });
        block.addEventListener('click', copy);
      });
    </script>
  </div>
</body>
</html>
