# Technical Instruction Specification: `data` Payload Integration (`datametric.md`)

This specification provides unambiguous, machine-readable instructions for an AI agent or developer implementing the frontend results layer in Svelte 5.

---

## 1. Input Contract & Detection Matrix

The frontend receives a unified backend response: `{ message: string, metrics: object, data: object }`.
The AI agent must identify the engine type and normalize `data` using the following detection sequence:

```typescript
function detectEngine(metrics, data) {
  if (Array.isArray(metrics?.cycles) && metrics.cycles.length > 0) {
    return "CONCURRENCY";
  }
  if (data && (data["0"] !== undefined || Array.isArray(data.finalresult))) {
    return "SEQUENCE";
  }
  return "APITESTS";
}
```

---

## 2. Parsing & Data Transformation Rules

### 2.1. Concurrency Engine (`data.diagnostics`)
* **Input Schema:**
  ```typescript
  data.diagnostics: Array<{
    status: number | null;
    data: string | object;
    headers?: Record<string, string>;
  }>
  ```
* **Required Transformation:**
  1. Group diagnostics by status code:
     ```typescript
     // Map: status -> { count: number, samples: string[] }
     const errorGroups = (data?.diagnostics || []).reduce((acc, curr) => {
       const key = curr.status ? String(curr.status) : "TIMEOUT/NETWORK";
       if (!acc[key]) acc[key] = { count: 0, samples: [] };
       acc[key].count += 1;
       const sampleText = typeof curr.data === "object" ? JSON.stringify(curr.data) : String(curr.data);
       if (acc[key].samples.length < 3) acc[key].samples.push(sampleText);
       return acc;
     }, {});
     ```
  2. Compute Primary Root Cause:
     - Find the status code with `max(count)`.
     - Extract for display: e.g. `"Primary error: 504 Gateway Timeout (68% of failures)"`.

### 2.2. Sequence Engine (`data[stepIndex]`)
* **Input Schema:**
  `data` contains numbered keys (`"0"`, `"1"`, ...) or array elements. Each element contains:
  ```typescript
  interface SequenceStepData {
    request: {
      endpoint?: string;
      link?: string;
      method: string;
      headers: Record<string, string>;
      data?: any;
    };
    response: {
      status: number;
      data: any;
      headers?: Record<string, string>;
    };
    conditionresult: [
      statusFlag: number, // 1 = passed, 0 = hard failed, -1 = warning/ignore, -2 = checkpoint
      details: {
        message?: string;
        nextdata?: any;
        nextheader?: any;
        [key: string]: any;
      },
      httpStatus: number
    ];
  }
  ```
* **Required Transformation:**
  1. Normalize `data` into a sequential step array:
     ```typescript
     const steps = Object.keys(data)
       .filter((k) => !isNaN(Number(k)))
       .sort((a, b) => Number(a) - Number(b))
       .map((k) => data[k]);
     ```
  2. Evaluate Condition Status per step:
     - If `conditionresult[0] === 1`: `stepStatus = "PASSED"`
     - If `conditionresult[0] === 0`: `stepStatus = "FAILED"`, `failureReason = conditionresult[1]?.message`
     - If `conditionresult[0] === -2`: `stepStatus = "CHECKPOINT"`

### 2.3. API Testing & Fuzzing Engine (`data` Schema)
* **Input Schema:**
  ```typescript
  data: {
    [paramName: string]: {
      type: "string" | "number" | "boolean" | "file" | "array" | "object";
      values: any[];
      range?: number[];
    }
  }
  ```
* **Required Transformation:**
  1. Compute Total Permutations and Tested Scope:
     ```typescript
     const paramKeys = Object.keys(data || {}).filter(k => typeof data[k] === "object" && Array.isArray(data[k].values));
     const totalCombinations = paramKeys.reduce((acc, k) => acc * (data[k].values.length || 1), 1);
     const summaryPill = `${paramKeys.length} Parameters • ${totalCombinations} Permutations`;
     ```
  2. Classify Value Types per parameter:
     - Detect presence of: `Null/Undefined`, `Empty string ("")`, `Boundary Numbers (<0, MAX_SAFE_INTEGER)`, `Security Payloads (SQLi/XSS substrings)`.

---

## 3. UI Component Wiring Instructions

The AI agent must NOT create a separate page-bottom section. Wire the transformed `data` into the following existing components:

### Instruction 3.1: Wire into `MetricCards.svelte`
* **Target:** Health Status KPI card & Total Requests card.
* **Conditional Actions:**
  * If `engine === "CONCURRENCY"` and `metrics.summary.totalRequestsFailed > 0`:
    * Render a secondary text node under the health badge with the calculated Primary Root Cause:
      `<span class="text-xs text-rose-400">Primary: {primaryRootCause}</span>`
  * If `engine === "APITESTS"` and `data` contains parameter keys:
    * Render a clickable pill below Total Requests count:
      `<button on:click={toggleScopePopover} class="badge-pill">{summaryPill}</button>`
    * Hover/click triggers a compact popover listing the parameters and value counts.

### Instruction 3.2: Wire into `CycleChart.svelte` (Concurrency Only)
* **Target:** Tooltip generation & bar click handlers.
* **Tooltips:**
  * When tooltip activates on cycle $N$:
    * Intersect `data.diagnostics` with cycle $N$'s failure count.
    * Append error status breakdown into the tooltip DOM:
      ```html
      <div class="tooltip-diagnostics">
        {#each cycleErrors as err}
          <div class="text-xs text-rose-300">{err.count}× {err.status}</div>
        {/each}
      </div>
      ```
* **Click Event:**
  * Clicking a cycle bar sets reactive state `activeCycleDrawer = cycleNum`.
  * Renders a slide-over drawer showing raw diagnostic error logs for that cycle.

### Instruction 3.3: Wire into `SequenceWaterfall.svelte` (Sequence Only)
* **Target:** Waterfall step items.
* **Inline Expansion:**
  * Clicking a step bar toggles an inline accordion row directly below that step:
    ```svelte
    {#if expandedStepIndex === index}
      <div class="p-3 bg-slate-950 rounded border border-slate-800 grid grid-cols-2 gap-2">
        <div>
          <span class="text-xs font-semibold text-slate-400">Request Sent:</span>
          <pre class="text-xs">{JSON.stringify(step.request, null, 2)}</pre>
        </div>
        <div>
          <span class="text-xs font-semibold text-slate-400">Response Received:</span>
          <pre class="text-xs">{JSON.stringify(step.response, null, 2)}</pre>
        </div>
        {#if step.conditionresult[0] === 0}
          <div class="col-span-2 text-rose-400 text-xs">
            Assertion Failed: {step.conditionresult[1]?.message}
          </div>
        {/if}
      </div>
    {/if}
    ```

---

## 4. Guardrails & Null Safety Rules

1. **`data` can be empty or null:**
   * Always apply optional chaining (`data?.diagnostics ?? []`).
   * If `data` is empty, components must degrade gracefully without throwing runtime TypeError exceptions.
2. **`data.diagnostics` entries can be unstructured:**
   * In `concurrencetest`, `diagnostic.data` can be a raw error string (e.g. `"Gateway Timeout"`), an object, or undefined. Always wrap JSON formatting in `try/catch` or use `typeof` checks before rendering.
3. **Single source of truth for counts:**
   * Do NOT recount requests from `data`. Always use `metrics.summary` and `metrics.latency.count` for aggregate counts. Use `data` strictly for context and qualitative attribution.
