// DAEV wiring init — added in Slice 6.4.5 wiring brief
// Orchestrates fixture hydration + dashboard list refresh from live backend.
// Runs once on DOMContentLoaded if API key is present.

(function() {
  // Phase A — Council mode pinned-replay for video filming.
  // When set, the Council Mode beat for the sqli fixture replays this
  // audit via the debate-stream SSE endpoint instead of firing a fresh
  // /switzerland/gate?mode=council POST — eliminating the council
  // cold-start latency risk on camera.
  // Operator populates this Wednesday evening after running:
  //   curl -X POST -H "X-DAEV-API-Key: $MASTER" \
  //     -H "Content-Type: application/json" \
  //     -d '{"source_code": "<sqli fixture>", "language": "python", "mode": "council"}' \
  //     https://daev-api.fly.dev/api/v1/switzerland/gate
  // Set back to null after filming to restore live council audits.
  window.PRESTAGED_COUNCIL_AUDIT_ID = '6c7a9b63-7598-4cf6-aa74-3f74a0c3e1e5';

  // Phase A — F-219 composite mitigation for video filming.
  // True = hide the Custom Paste chip, forcing operator to
  // pre-rehearsed fixture chips only. Set false post-recording.
  window.DAEV_HIDE_CUSTOM_PASTE = true;

  // UI fixture id → backend prestaged audit_id (per Probe B10 mapping).
  // Slice 6.4.5.2 Phase 11 (BUG-81 / Phase 7): re-prestaged after the
  // metadata-persistence + cwe_id + sast_data + extended SYMBOLIC_PATTERNS
  // backend changes deployed (commits 1b64dbd → 4839e32). All 4 audits now
  // carry real cognitive_signals + cwe_id + sast_data on GET.
  const FIXTURE_AUDIT_MAP = {
    'sqli':      '3ba75145-bdb8-4091-8257-a8adc6592761',
    'cmdi':      '34b8ba47-55a1-4c56-bb02-a9973be73f2d',
    'pathtrav':  '74268b96-c45e-4df4-bb0b-c0eae5162533',
    'hardcoded': '12a2c07a-325d-4b8d-bad4-d06b7c36e0ac',
    // 'safe', 'xss-js', 'cmdi-js', 'racecond' — keep static (no backend equivalent)
  };

  // Slice 6.4.7 Phase 5 (HC-53): pre-staged GitHub-audit lookup map.
  // When the user pastes one of these repo URLs, the UI short-circuits
  // to the prestaged audit_id (instant Beat 4 demo) instead of running
  // the 30-90 s github audit pipeline. Audit_ids are real backend
  // records produced by ``POST /audits/from-github`` post-Phase-1
  // deploy — the multi-scope graph is the F-204 fix demo artefact.
  // The backfill happens in Phase 7 once the new backend is live; this
  // map starts empty so the path is wired but inert until that step.
  // HC-53: NEVER fabricate audit data here — empty until a real
  // backend audit_id is captured.
  //
  // Slice 6.4.7 Phase 7 post-deploy backfill: DVPWA audit_id captured
  // 2026-05-08 against the freshly-deployed multi-scope-graph backend.
  // Verified: 8 scope keys, 112 nodes, 61 edges, finding_count=1 (CWE-798).
  // F-204 GREEN — graph_json populated end-to-end.
  const PRESTAGED_GITHUB_AUDITS = {
    'github.com/anxolerd/dvpwa': 'dc007612-0e2b-4136-8f12-501c0b8b2caf',
  };

  function _normalizeRepoUrl(repoUrl) {
    if (!repoUrl) return '';
    return String(repoUrl)
      .replace(/^https?:\/\//, '')
      .replace(/\.git$/, '')
      .replace(/\/$/, '')
      .toLowerCase();
  }

  // Public: handleGitHubAudit-style short-circuit. Caller (app.jsx
  // handleRunGithubAudit) checks this BEFORE submitting a fresh audit.
  // Returns null on miss; on hit returns the wired fixture-shape object
  // (same shape apiAuditToFixtureShape produces).
  async function getPrestagedGithubAudit(repoUrl) {
    const key = _normalizeRepoUrl(repoUrl);
    const audit_id = PRESTAGED_GITHUB_AUDITS[key];
    if (!audit_id) return null;
    if (!window.DAEV_API || !window.DAEV_TRANSFORM) return null;
    try {
      const detail = await window.DAEV_API.fetchAuditDetail(audit_id);
      const wired = window.DAEV_TRANSFORM.apiAuditToFixtureShape(
        detail, null, '_github_live'
      );
      if (wired) {
        wired.audit_metadata = wired.audit_metadata || {};
        wired.audit_metadata.repo_url = repoUrl;
        wired.audit_metadata.source = 'github-prestaged';
      }
      return wired;
    } catch (e) {
      console.warn(
        `[daev-wiring] prestaged github lookup failed for ${key}: ${e.message}`
      );
      return null;
    }
  }

  // Hydrate the 4 wired fixtures + dashboard list
  async function hydrateAll() {
    if (!window.DAEV_API || !window.DAEV_TRANSFORM) {
      console.warn('[daev-wiring] DAEV_API or DAEV_TRANSFORM not loaded; aborting hydration');
      return;
    }
    if (!window.DAEV_FIXTURES) {
      console.warn('[daev-wiring] DAEV_FIXTURES not loaded; aborting hydration');
      return;
    }

    const apiKey = window.DAEV_API.getApiKey();
    if (!apiKey) {
      console.log('[daev-wiring] no API key; skipping live hydration (fixtures stay static)');
      return;
    }

    console.log('[daev-wiring] starting hydration of', Object.keys(FIXTURE_AUDIT_MAP).length, 'fixtures');

    // Fire warm in background (non-blocking)
    window.DAEV_API.warmDemo().catch(e => console.warn('[daev-wiring] warm failed:', e.message));

    // Slice 6.4.5.2 Phase 10 (BUG-78): per-fixture SAST cache so SastPanel
    // can render real per-tool data per fixture (instead of one shared static
    // window.DAEV_SAST blob).
    window.DAEV_SAST_BY_FIXTURE = window.DAEV_SAST_BY_FIXTURE || {};

    // Hydrate each fixture in parallel
    const tasks = Object.entries(FIXTURE_AUDIT_MAP).map(async ([ui_id, audit_id]) => {
      try {
        const detail = await window.DAEV_API.fetchAuditDetail(audit_id);
        const sourceResp = await window.DAEV_API.fetchAuditSource(audit_id);
        const sourceLines = (sourceResp && sourceResp.source)
          ? sourceResp.source.split('\n')
          : null;
        const wired = window.DAEV_TRANSFORM.apiAuditToFixtureShape(detail, sourceLines, ui_id);
        if (!wired) {
          console.warn(`[daev-wiring] ${ui_id} transform returned null; keeping static`);
          return;
        }
        // Preserve original `lines` if backend didn't return source (UI editor shows them)
        if (!sourceLines && window.DAEV_FIXTURES[ui_id] && window.DAEV_FIXTURES[ui_id].lines) {
          wired.lines = window.DAEV_FIXTURES[ui_id].lines;
        }
        window.DAEV_FIXTURES[ui_id] = wired;
        console.log(`[daev-wiring] ✓ ${ui_id} hydrated from ${audit_id} (${wired.graph.nodes.length} nodes)`);

        // Slice 6.4.5.2 Phase 10 (BUG-78): hydrate per-fixture SAST data.
        // Non-blocking — if /sast 404s or returns available=false, the panel
        // gracefully falls back to the static window.DAEV_SAST.
        try {
          const sastData = await window.DAEV_API.fetchAuditSast(audit_id);
          if (sastData && sastData.available) {
            window.DAEV_SAST_BY_FIXTURE[ui_id] = sastData;
            console.log(`[daev-wiring] ✓ ${ui_id} SAST hydrated: ${(sastData.tools || []).length} tools, ${sastData.total_findings} findings`);
          } else {
            console.log(`[daev-wiring]   ${ui_id} SAST not available (legacy audit)`);
          }
        } catch (sastErr) {
          console.warn(`[daev-wiring]   ${ui_id} SAST fetch failed:`, sastErr.message);
        }
      } catch (e) {
        console.warn(`[daev-wiring] ✗ ${ui_id} hydration failed:`, e.message);
        // Static fixture remains; no demo regression
      }
    });
    await Promise.allSettled(tasks);

    // Refresh dashboard list (best-effort; static fallback if it fails)
    try {
      const list = await window.DAEV_API.fetchAudits();
      const items = (list && list.items) || [];
      if (items.length > 0) {
        // Prepend wired audits to the existing static list (don't fully replace — preserves
        // demo-friendly fixtures like 'safe', 'xss-js', etc. that have no backend equivalent)
        const wiredRows = items.slice(0, 8).map(window.DAEV_TRANSFORM.apiAuditListItemToRow);
        const staticRows = (window.DAEV_AUDITS || []).filter(r =>
          ['safe', 'xss-js', 'cmdi-js', 'racecond'].includes(r.fix)
        );
        window.DAEV_AUDITS = [...wiredRows, ...staticRows].slice(0, 12);
        console.log(`[daev-wiring] ✓ dashboard list refreshed (${wiredRows.length} wired + ${staticRows.length} static)`);
      }
    } catch (e) {
      console.warn('[daev-wiring] dashboard list refresh failed:', e.message);
    }

    // Notify React to re-render
    window.dispatchEvent(new CustomEvent('daev-fixtures-hydrated', {
      detail: { count: Object.keys(FIXTURE_AUDIT_MAP).length, ts: Date.now() }
    }));
    console.log('[daev-wiring] hydration complete; daev-fixtures-hydrated event fired');
  }

  // Expose for debugging + manual re-hydration
  window.DAEV_WIRING = {
    FIXTURE_AUDIT_MAP,
    PRESTAGED_GITHUB_AUDITS,
    hydrateAll,
    getPrestagedGithubAudit,
  };

  // Auto-fire on load (if API key is present)
  if (typeof window !== 'undefined') {
    if (document.readyState === 'loading') {
      window.addEventListener('DOMContentLoaded', hydrateAll);
    } else {
      // DOM already loaded
      setTimeout(hydrateAll, 100);
    }
  }
})();
