import { Callout } from "../components/Callout";
import { CodeBlock } from "../components/CodeBlock";

export function MonitoringGuide() {
  return (
    <div>
      <h1 id="monitoring">Monitoring & Alerting</h1>
      <p>
        Veylant IA exposes Prometheus metrics and ships pre-built Grafana dashboards and
        Alertmanager rules for production operations.
      </p>

      <h2 id="prometheus">Prometheus Metrics</h2>
      <p>
        The proxy exposes metrics at <code>GET /metrics</code> (Prometheus text format, scraped
        every 15 seconds).
      </p>

      <div className="overflow-x-auto my-4">
        <table className="w-full text-sm border rounded-lg overflow-hidden">
          <thead>
            <tr className="bg-muted/50 border-b">
              <th className="text-left px-4 py-2.5 font-semibold">Metric</th>
              <th className="text-left px-4 py-2.5 font-semibold">Type</th>
              <th className="text-left px-4 py-2.5 font-semibold">Description</th>
            </tr>
          </thead>
          <tbody>
            {[
              { metric: "veylant_requests_total", type: "Counter", desc: "Total requests by provider, model, status_code, tenant_id" },
              { metric: "veylant_request_duration_seconds", type: "Histogram", desc: "End-to-end request latency (p50, p95, p99)" },
              { metric: "veylant_pii_entities_total", type: "Counter", desc: "PII entities detected by type" },
              { metric: "veylant_tokens_total", type: "Counter", desc: "Tokens consumed by provider and model" },
              { metric: "veylant_cost_usd_total", type: "Counter", desc: "USD cost by provider and model" },
              { metric: "veylant_circuit_breaker_state", type: "Gauge", desc: "Circuit breaker state (0=closed, 1=open, 2=half-open) by provider" },
              { metric: "veylant_rate_limit_rejections_total", type: "Counter", desc: "Rate limit rejections by tenant_id" },
              { metric: "veylant_pii_pipeline_duration_seconds", type: "Histogram", desc: "PII detection pipeline latency" },
              { metric: "veylant_db_connections", type: "Gauge", desc: "PostgreSQL connection pool (open, idle, in-use)" },
            ].map((row) => (
              <tr key={row.metric} className="border-b last:border-0">
                <td className="px-4 py-2.5 font-mono text-xs">{row.metric}</td>
                <td className="px-4 py-2.5 text-xs">
                  <span className={`px-1.5 py-0.5 rounded text-xs font-medium ${row.type === "Counter" ? "bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300" : row.type === "Gauge" ? "bg-green-100 dark:bg-green-900/40 text-green-700 dark:text-green-300" : "bg-purple-100 dark:bg-purple-900/40 text-purple-700 dark:text-purple-300"}`}>
                    {row.type}
                  </span>
                </td>
                <td className="px-4 py-2.5 text-xs text-muted-foreground">{row.desc}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <h2 id="grafana-dashboards">Grafana Dashboards</h2>
      <p>
        Two dashboards are pre-provisioned in Grafana (<code>http://localhost:3001</code>,
        admin/admin):
      </p>

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 my-4">
        <div className="rounded-lg border bg-card p-4">
          <h3 className="font-semibold text-sm mb-2">Proxy Overview</h3>
          <ul className="text-sm text-muted-foreground space-y-1">
            <li>Request rate (req/min)</li>
            <li>Error rate (%)</li>
            <li>Latency p50/p95/p99</li>
            <li>Token consumption over time</li>
            <li>PII entities by type</li>
            <li>Provider distribution (pie chart)</li>
            <li>DB connection pool</li>
          </ul>
        </div>
        <div className="rounded-lg border bg-card p-4">
          <h3 className="font-semibold text-sm mb-2">Production SLO</h3>
          <ul className="text-sm text-muted-foreground space-y-1">
            <li>SLO: 99.5% availability</li>
            <li>Error budget (burn rate)</li>
            <li>p95 latency SLO (&lt;500ms)</li>
            <li>Error budget remaining (%)</li>
            <li>Active incidents timeline</li>
          </ul>
        </div>
      </div>

      <h2 id="alerts">Prometheus Alerts</h2>
      <p>
        7 alert rules are configured in <code>deploy/prometheus/rules.yml</code> and integrated
        with Alertmanager:
      </p>

      <div className="space-y-3 my-4">
        {[
          { name: "HighLatency", severity: "warning", desc: "p95 latency > 500ms for 2 minutes", expr: "histogram_quantile(0.95, veylant_request_duration_seconds_bucket) > 0.5" },
          { name: "HighErrorRate", severity: "critical", desc: "Error rate > 5% for 1 minute", expr: "rate(veylant_requests_total{status_code=~'5..'}[1m]) / rate(veylant_requests_total[1m]) > 0.05" },
          { name: "CircuitBreakerOpen", severity: "warning", desc: "Any provider circuit breaker is open", expr: "veylant_circuit_breaker_state > 0" },
          { name: "ProxyDown", severity: "critical", desc: "Proxy health check failing", expr: "up{job='veylant-proxy'} == 0" },
          { name: "CertExpiry", severity: "warning", desc: "TLS certificate expires in < 7 days", expr: "probe_ssl_earliest_cert_expiry - time() < 7 * 86400" },
          { name: "DBConnPoolExhausted", severity: "warning", desc: "DB connection pool > 90% utilized", expr: "veylant_db_connections{state='in_use'} / (veylant_db_connections{state='in_use'} + veylant_db_connections{state='idle'}) > 0.9" },
          { name: "PIIAnomaly", severity: "warning", desc: "PII detection rate spiked > 3x baseline", expr: "rate(veylant_pii_entities_total[5m]) > 3 * avg_over_time(rate(veylant_pii_entities_total[5m])[1h:])" },
        ].map((alert) => (
          <div key={alert.name} className="rounded-lg border bg-card p-4">
            <div className="flex items-center gap-2 mb-1">
              <span className="font-mono text-sm font-semibold">{alert.name}</span>
              <span className={`text-xs px-1.5 py-0.5 rounded font-medium ${alert.severity === "critical" ? "bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300" : "bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300"}`}>
                {alert.severity}
              </span>
            </div>
            <p className="text-sm text-muted-foreground mb-2">{alert.desc}</p>
            <code className="text-xs text-muted-foreground bg-muted px-2 py-1 rounded block overflow-x-auto">
              {alert.expr}
            </code>
          </div>
        ))}
      </div>

      <h2 id="alertmanager">Alertmanager Routing</h2>
      <p>Alerts are routed based on severity:</p>
      <ul>
        <li>
          <strong>Critical</strong> → PagerDuty (immediate on-call notification)
        </li>
        <li>
          <strong>Warning</strong> → Slack (#veylant-alerts channel)
        </li>
      </ul>
      <CodeBlock
        language="yaml"
        code={`# deploy/alertmanager/alertmanager.yml
route:
  group_by: ['alertname', 'severity']
  group_wait: 30s
  group_interval: 5m
  repeat_interval: 12h
  receiver: slack-warnings

  routes:
    - match:
        severity: critical
      receiver: pagerduty-critical

receivers:
  - name: pagerduty-critical
    pagerduty_configs:
      - routing_key: PAGERDUTY_ROUTING_KEY
  - name: slack-warnings
    slack_configs:
      - channel: '#veylant-alerts'`}
      />

      <h2 id="slo">SLO Definition</h2>
      <Callout type="info" title="Production SLO — v1.0.0">
        <strong>Availability:</strong> 99.5% (allows ~3.6 hours downtime/month)
        <br />
        <strong>Latency:</strong> p95 &lt; 500ms for chat completion requests
        <br />
        <strong>PII pipeline:</strong> p99 &lt; 50ms
        <br />
        <strong>Error rate:</strong> &lt; 0.5% (5xx responses)
      </Callout>
    </div>
  );
}
