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

export function AdminCompliancePage() {
  return (
    <div>
      <h1 id="admin-compliance">Admin — Compliance</h1>
      <p>
        GDPR Article 30 processing registry, EU AI Act risk classification, DPIA generation, PDF
        reports, CSV export, and GDPR subject rights (access and erasure). All endpoints are mounted
        under <code>/v1/admin/compliance</code> and require a valid JWT.
      </p>

      <Callout type="info" title="Required role">
        Read endpoints (<code>GET</code>) are accessible to <code>admin</code> and{" "}
        <code>auditor</code> roles. Write endpoints (<code>POST</code>, <code>PUT</code>,{" "}
        <code>DELETE</code>) require <code>admin</code>.
      </Callout>

      <h2 id="processing-registry">GDPR Article 30 — Processing Registry</h2>
      <p>
        Every AI use case that may process personal data must be documented in the registry. The
        compliance module generates the legally required Article 30 register directly from these
        entries.
      </p>

      <ApiEndpoint method="GET" path="/v1/admin/compliance/entries" description="List all processing activities for the authenticated tenant." />
      <ApiEndpoint method="POST" path="/v1/admin/compliance/entries" description="Create a new processing activity entry." />
      <ApiEndpoint method="GET" path="/v1/admin/compliance/entries/{id}" description="Get a specific processing entry by ID." />
      <ApiEndpoint method="PUT" path="/v1/admin/compliance/entries/{id}" description="Update a processing activity. AI Act classification (risk_level, ai_act_answers) is preserved automatically." />
      <ApiEndpoint method="DELETE" path="/v1/admin/compliance/entries/{id}" description="Soft-delete a processing entry (is_active = false)." />

      <ParamTable
        title="Processing Entry Fields"
        params={[
          { name: "use_case_name", type: "string", required: true, description: "Name of the AI use case (e.g. 'Legal contract analysis')." },
          { name: "purpose", type: "string", required: true, description: "Processing purpose as required by GDPR Art. 5(1)(b)." },
          { name: "legal_basis", type: "string", required: true, description: "Legal basis: consent | contract | legal_obligation | vital_interests | public_task | legitimate_interest" },
          { name: "data_categories", type: "[]string", required: true, description: "Categories of personal data: name, email, phone, id_number, financial, health, biometric, etc." },
          { name: "retention_period", type: "string", required: true, description: "Data retention period (e.g. '3 years', '90 days', '6 months after contract end')." },
          { name: "security_measures", type: "string", required: false, description: "Technical and organizational security measures in place." },
          { name: "controller_name", type: "string", required: false, description: "Data controller name and DPO contact." },
          { name: "recipients", type: "[]string", required: false, description: "Third parties receiving the data (e.g. 'OpenAI via Veylant IA proxy')." },
          { name: "processors", type: "[]string", required: false, description: "Sub-processors involved in the processing." },
        ]}
      />

      <CodeBlock
        language="bash"
        code={`# Create a processing entry
curl -X POST http://localhost:8090/v1/admin/compliance/entries \\
  -H "Authorization: Bearer $TOKEN" \\
  -H "Content-Type: application/json" \\
  -d '{
    "use_case_name": "Analyse de contrats fournisseurs",
    "purpose": "Identification automatique des risques dans les contrats fournisseurs",
    "legal_basis": "legitimate_interest",
    "data_categories": ["name", "financial", "company_data"],
    "retention_period": "3 ans",
    "security_measures": "Chiffrement AES-256-GCM, anonymisation PII, logs d'\''audit immuables",
    "controller_name": "Acme Corp — dpo@acme.com",
    "processors": ["Anthropic (Claude via Veylant IA proxy)"],
    "recipients": []
  }'`}
      />

      <CodeBlock
        language="json"
        code={`// 201 — Entry created
{
  "id": "ce4f1234-0000-0000-0000-000000000001",
  "tenant_id": "dev-tenant",
  "use_case_name": "Analyse de contrats fournisseurs",
  "purpose": "Identification automatique des risques dans les contrats fournisseurs",
  "legal_basis": "legitimate_interest",
  "data_categories": ["name", "financial", "company_data"],
  "retention_period": "3 ans",
  "security_measures": "Chiffrement AES-256-GCM, anonymisation PII, logs d'audit immuables",
  "controller_name": "Acme Corp — dpo@acme.com",
  "processors": ["Anthropic (Claude via Veylant IA proxy)"],
  "recipients": [],
  "risk_level": "",
  "ai_act_answers": null,
  "is_active": true,
  "created_at": "2026-03-12T09:00:00Z",
  "updated_at": "2026-03-12T09:00:00Z"
}`}
      />

      <Callout type="tip" title="AI Act classification is preserved on update">
        When you <code>PUT</code> an entry, the <code>risk_level</code> and{" "}
        <code>ai_act_answers</code> fields are automatically carried over from the existing record.
        Editing the registry never resets a previously computed classification.
      </Callout>

      <h2 id="ai-act">EU AI Act Classification</h2>
      <ApiEndpoint
        method="POST"
        path="/v1/admin/compliance/entries/{id}/classify"
        description="Run the 5-question AI Act risk questionnaire. Updates risk_level and ai_act_answers on the entry."
      />

      <p>The questionnaire uses 5 boolean keys (<code>q1</code>–<code>q5</code>):</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">Key</th>
              <th className="text-left px-4 py-2.5 font-semibold">Question</th>
            </tr>
          </thead>
          <tbody>
            {[
              { key: "q1", q: "Le système prend-il des décisions autonomes affectant des droits légaux ou des situations similaires ?" },
              { key: "q2", q: "Implique-t-il une identification biométrique ou une reconnaissance des émotions ?" },
              { key: "q3", q: "Est-il utilisé dans des décisions critiques (médical, justice, emploi, crédit) ?" },
              { key: "q4", q: "Traite-t-il des catégories spéciales de données (santé, biométrie, origine raciale) ?" },
              { key: "q5", q: "La transparence sur l'utilisation de l'IA est-elle indispensable au consentement éclairé ?" },
            ].map((row) => (
              <tr key={row.key} className="border-b last:border-0">
                <td className="px-4 py-2.5 font-mono text-xs font-bold">{row.key}</td>
                <td className="px-4 py-2.5 text-muted-foreground text-xs">{row.q}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <p>Scoring: count the number of <code>true</code> answers.</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">Yes answers</th>
              <th className="text-left px-4 py-2.5 font-semibold">risk_level</th>
              <th className="text-left px-4 py-2.5 font-semibold">Implication</th>
            </tr>
          </thead>
          <tbody>
            {[
              { score: "5", level: "forbidden", color: "text-red-600", desc: "Déploiement interdit (ex: notation sociale, surveillance biométrique en temps réel dans l'espace public)." },
              { score: "3–4", level: "high", color: "text-orange-600", desc: "Évaluation de conformité obligatoire. AIPD/DPIA requise avant déploiement." },
              { score: "1–2", level: "limited", color: "text-amber-600", desc: "Obligations de transparence : les utilisateurs doivent être informés qu'ils interagissent avec une IA." },
              { score: "0", level: "minimal", color: "text-green-600", desc: "Risque minimal. Code de conduite volontaire recommandé." },
            ].map((row) => (
              <tr key={row.level} className="border-b last:border-0">
                <td className="px-4 py-2.5 font-mono text-xs">{row.score}</td>
                <td className={`px-4 py-2.5 font-semibold text-xs font-mono ${row.color}`}>{row.level}</td>
                <td className="px-4 py-2.5 text-muted-foreground text-xs">{row.desc}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <CodeBlock
        language="bash"
        code={`# Classify an entry — chatbot answering FAQ (limited risk)
curl -X POST http://localhost:8090/v1/admin/compliance/entries/ce4f1234-0000-0000-0000-000000000001/classify \\
  -H "Authorization: Bearer $TOKEN" \\
  -H "Content-Type: application/json" \\
  -d '{
    "answers": {
      "q1": false,
      "q2": false,
      "q3": false,
      "q4": false,
      "q5": true
    }
  }'`}
      />

      <CodeBlock
        language="json"
        code={`// 200 — Returns the updated ProcessingEntry
{
  "id": "ce4f1234-0000-0000-0000-000000000001",
  "use_case_name": "Analyse de contrats fournisseurs",
  "risk_level": "limited",
  "ai_act_answers": {
    "q1": false,
    "q2": false,
    "q3": false,
    "q4": false,
    "q5": true
  },
  "is_active": true,
  ...
}`}
      />

      <h2 id="reports">PDF & JSON Reports</h2>
      <p>
        Reports stream directly as PDF (default) or JSON (<code>?format=json</code>). No polling
        required — the response is the file.
      </p>

      <ApiEndpoint method="GET" path="/v1/admin/compliance/report/article30" description="GDPR Art. 30 register for the tenant. PDF by default, JSON with ?format=json." />
      <ApiEndpoint method="GET" path="/v1/admin/compliance/report/aiact" description="EU AI Act risk classification report for all entries. PDF by default, JSON with ?format=json." />
      <ApiEndpoint method="GET" path="/v1/admin/compliance/dpia/{id}" description="DPIA template PDF for a specific processing entry." />

      <CodeBlock
        language="bash"
        code={`# Download GDPR Art. 30 register as PDF
curl "http://localhost:8090/v1/admin/compliance/report/article30" \\
  -H "Authorization: Bearer $TOKEN" \\
  --output article30_register.pdf

# Download as JSON (for custom reporting tools)
curl "http://localhost:8090/v1/admin/compliance/report/article30?format=json" \\
  -H "Authorization: Bearer $TOKEN"

# Download AI Act risk classification report as PDF
curl "http://localhost:8090/v1/admin/compliance/report/aiact" \\
  -H "Authorization: Bearer $TOKEN" \\
  --output aiact_report.pdf

# Generate DPIA for a specific high-risk entry
curl "http://localhost:8090/v1/admin/compliance/dpia/ce4f1234-0000-0000-0000-000000000001" \\
  -H "Authorization: Bearer $TOKEN" \\
  --output dpia_contract_analysis.pdf`}
      />

      <Callout type="tip" title="PDF headers use server.tenant_name">
        PDF reports display the organisation name configured in <code>server.tenant_name</code>{" "}
        (config.yaml). Set this to your legal entity name for compliance documentation.
      </Callout>

      <h2 id="csv-export">Audit Log CSV Export</h2>
      <ApiEndpoint
        method="GET"
        path="/v1/admin/compliance/export/logs"
        description="Export audit logs as CSV (max 10 000 rows). Accepts RFC3339 or YYYY-MM-DD date format for start/end."
      />

      <CodeBlock
        language="bash"
        code={`# Export all audit logs
curl "http://localhost:8090/v1/admin/compliance/export/logs" \\
  -H "Authorization: Bearer $TOKEN" \\
  --output audit_export.csv

# Export for Q1 2026 using simple date format
curl "http://localhost:8090/v1/admin/compliance/export/logs?start=2026-01-01&end=2026-03-31" \\
  -H "Authorization: Bearer $TOKEN" \\
  --output q1_2026_audit.csv`}
      />

      <h2 id="gdpr-rights">GDPR Subject Rights</h2>

      <h3 id="access">Article 15 — Right of Access</h3>
      <ApiEndpoint
        method="GET"
        path="/v1/admin/compliance/gdpr/access/{user_id}"
        description="Return all audit log entries for a specific user (up to 1 000 records). Used to respond to GDPR Art. 15 subject access requests."
      />
      <CodeBlock
        language="bash"
        code={`curl "http://localhost:8090/v1/admin/compliance/gdpr/access/a1b2c3d4-0000-0000-0000-000000000001" \\
  -H "Authorization: Bearer $TOKEN"`}
      />

      <CodeBlock
        language="json"
        code={`// 200 — All audit entries for the user
{
  "user_id": "a1b2c3d4-0000-0000-0000-000000000001",
  "generated_at": "2026-03-12T10:00:00Z",
  "total": 47,
  "records": [
    {
      "request_id": "req_01HV...",
      "timestamp": "2026-03-10T14:32:11Z",
      "provider": "anthropic",
      "model_used": "claude-3-5-sonnet-20241022",
      "sensitivity_level": "high",
      "pii_entity_count": 3,
      "status": "ok"
    }
  ]
}`}
      />

      <h3 id="erasure">Article 17 — Right to Erasure</h3>
      <ApiEndpoint
        method="DELETE"
        path="/v1/admin/compliance/gdpr/erase/{user_id}"
        description="Soft-delete the user account (is_active = false) and log the erasure request to the gdpr_erasure_log table."
      />
      <CodeBlock
        language="bash"
        code={`curl -X DELETE "http://localhost:8090/v1/admin/compliance/gdpr/erase/a1b2c3d4-0000-0000-0000-000000000001" \\
  -H "Authorization: Bearer $TOKEN" \\
  -H "Content-Type: application/json" \\
  -d '{"reason": "Demande utilisateur conformément au RGPD Art. 17"}'`}
      />

      <CodeBlock
        language="json"
        code={`// 200 — Erasure confirmed
{
  "erasure_id": "er9a0000-0000-0000-0000-000000000042",
  "tenant_id": "dev-tenant",
  "user_id": "a1b2c3d4-0000-0000-0000-000000000001",
  "requested_by": "admin@veylant.dev",
  "reason": "Demande utilisateur conformément au RGPD Art. 17",
  "records_deleted": 1,
  "status": "completed",
  "timestamp": "2026-03-12T10:05:00Z"
}`}
      />

      <Callout type="warning" title="Soft-delete — ClickHouse logs are append-only">
        The erasure endpoint sets <code>users.is_active = false</code> in PostgreSQL. ClickHouse
        audit logs are append-only and cannot be deleted; request metadata (token counts, cost,
        timestamps) is retained for compliance reporting. The <code>gdpr_erasure_log</code> table
        provides an immutable audit trail of all erasure actions.
      </Callout>
    </div>
  );
}
