// Dev-only intelligence surface — /dev/intelligence?tenant=<id> or
// /{company-slug}/dev-intelligence. Dumps the full structured SignalSet the
// evaluator produces for the currently-loaded tenant. Internal verification
// tool, NOT customer-facing (no styling polish, no narrative — raw signal set).
//
// It loads the three catalog YAMLs (js-yaml), folds the app's live `data` into
// a DataContext, runs globalThis.PerduraIntelligence.evaluate, and renders the
// result as JSON. Also exposes window.__perduraSignalSet for the e2e harness.

(function () {
  const R = window.React;
  if (!R) return;

  const CATALOG_URLS = {
    metrics: "/src/intelligence/catalogs/metrics.yaml",
    exceptions: "/src/intelligence/catalogs/exceptions.yaml",
    opportunities: "/src/intelligence/catalogs/opportunities.yaml",
  };

  let _catalogTextCache = null;
  async function loadCatalogText() {
    if (_catalogTextCache) return _catalogTextCache;
    const entries = await Promise.all(
      Object.keys(CATALOG_URLS).map(async (k) => {
        const res = await fetch(CATALOG_URLS[k] + "?v=" + Date.now());
        if (!res.ok) throw new Error("fetch " + CATALOG_URLS[k] + " -> " + res.status);
        return [k, await res.text()];
      })
    );
    _catalogTextCache = {};
    entries.forEach(([k, v]) => (_catalogTextCache[k] = v));
    return _catalogTextCache;
  }

  function DevIntelligencePage(props) {
    const data = props.data || window.__perduraLiveData;
    const profile = props.companyProfile || window.__perduraProfile;
    const [state, setState] = R.useState({ status: "idle", signalSet: null, error: null });

    R.useEffect(() => {
      let cancelled = false;
      async function run() {
        try {
          if (!window.PerduraIntelligence || !window.PerduraIntelligence.run) {
            setState({ status: "loading-engine", signalSet: null, error: null });
            return;
          }
          if (!window.jsyaml) throw new Error("js-yaml not loaded");
          if (!data || (!data.plHistory && !data.txns)) {
            window.__perduraSignalSet = { error: "no-data", has_data: !!data, data_keys: data ? Object.keys(data) : [], settled: window.PerduraDataState && window.PerduraDataState.settled };
            setState({ status: "no-data", signalSet: null, error: null });
            return;
          }
          setState({ status: "running", signalSet: null, error: null });
          const text = await loadCatalogText();
          const parse = (s) => window.jsyaml.load(s);
          const signalSet = window.PerduraIntelligence.run(text, data, profile, parse);
          if (cancelled) return;
          window.__perduraSignalSet = signalSet;
          setState({ status: "done", signalSet: signalSet, error: null });
        } catch (e) {
          if (cancelled) return;
          window.__perduraSignalSet = { error: String(e && e.message || e) };
          setState({ status: "error", signalSet: null, error: String(e && e.stack || e) });
        }
      }
      run();
      // retry once shortly if the babel-transpiled engine hasn't attached yet
      const t = setTimeout(() => { if (!cancelled && !window.__perduraSignalSet) run(); }, 600);
      return () => { cancelled = true; clearTimeout(t); };
    }, [data, profile]);

    const mono = { fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace", fontSize: 12 };
    const wrap = { padding: 20, color: "var(--text-1, #111)" };

    if (state.status !== "done") {
      return R.createElement("div", { style: wrap, "data-dev-intelligence": state.status },
        R.createElement("h2", null, "Intelligence — SignalSet (dev)"),
        R.createElement("p", { style: mono }, "status: " + state.status),
        state.error ? R.createElement("pre", { style: { ...mono, color: "#b91c1c", whiteSpace: "pre-wrap" } }, state.error) : null
      );
    }

    const ss = state.signalSet;
    const summary = {
      company_id: ss.company_id, archetype: ss.archetype, industry: ss.industry,
      window: ss.generated_window, counts: ss.counts, diagnostics: ss.diagnostics,
    };
    const top3 = ss.signals.filter((s) => s.estimated_dollar_impact).slice(0, 3)
      .map((s) => ({ id: s.id, name: s.name, severity: s.severity, impact: s.estimated_dollar_impact }));

    return R.createElement("div", { style: wrap, "data-dev-intelligence": "done" },
      R.createElement("h2", null, "Intelligence — SignalSet (dev)"),
      R.createElement("div", { style: { ...mono, marginBottom: 8 } },
        ss.archetype + " · " + ss.industry + " · " + ss.counts.total + " signals"),
      R.createElement("h3", null, "Summary"),
      R.createElement("pre", { id: "dev-intel-summary", style: { ...mono, whiteSpace: "pre-wrap", background: "var(--surface-2,#f6f7f9)", padding: 12, borderRadius: 6 } },
        JSON.stringify(summary, null, 2)),
      R.createElement("h3", null, "Top dollar-impact signals"),
      R.createElement("pre", { style: { ...mono, whiteSpace: "pre-wrap" } }, JSON.stringify(top3, null, 2)),
      R.createElement("h3", null, "Full SignalSet"),
      R.createElement("pre", { id: "dev-intel-json", style: { ...mono, whiteSpace: "pre-wrap", background: "var(--surface-2,#f6f7f9)", padding: 12, borderRadius: 6 } },
        JSON.stringify(ss, null, 2))
    );
  }

  window.DevIntelligencePage = DevIntelligencePage;
})();
