// What the machine was asked, and what it cost (AI-7, 0105).
//
// WHAT THIS PANE IS. `cw.model_call` has recorded every question this product
// put to a model since 0066 — eight declared purposes, who caused each call,
// what came back, and what the provider said it cost. Nothing could read it
// until 0105: no view, no endpoint, no screen. This is the screen.
//
// IT IS THE EVIDENCE BEHIND EVERY AI PROMISE THIS PRODUCT MAKES. A legal team
// that cannot see what the machine was asked is taking the rest on trust.
//
// THREE OUTCOMES, DRAWN AS THREE. Collapsing them misstates two figures at
// once, so nothing here shows a bare "calls" number as spend:
//
//   answered   asked, a usable answer came back.        BILLED.
//   absent     asked, nothing usable came back.         BILLED — the provider
//                                                       did the work.
//   not asked  the doorway declined to dispatch at all. COST NOTHING.
//
// On a deployment with no key EVERY row is `not asked`, which is the state
// every machine in this repository is in — so a screen that read "calls" as
// spend would report a bill that does not exist.
//
// AND A TOTAL THAT CANNOT BE QUALIFIED IS NOT SHOWN AS A TOTAL. The provider
// does not always report usage; 0066 stores that as unknown rather than zero,
// "because a zero here would understate spend in exactly the figure somebody
// budgets from". `sum()` skips nulls silently, so wherever a total appears
// here, the count of billed calls it could not cost appears beside it.
function AiUsePane({ me }) {
  const record = usePane(() => API.aiUse());
  const byPurpose = usePane(() => API.aiUseByPurpose());
  // WHAT THE PARAGRAPH INDEX PAID FOR TWICE (0114). Its own hook, above every
  // return, because a hook after an early return blanks the whole file.
  const reuse = usePane(() => API.paragraphReuse());
  const filter = useListFilter(record.rows ?? [], {
    view: 'ai-use:record',
    fields: ['purpose', 'actor', 'model', 'outcome'],
    facet: 'outcome',
  });

  if (record.loading || byPurpose.loading) return <Loading />;
  if (record.failed) return <LoadFailed reason={record.failed.reason} />;
  if (byPurpose.failed) return <LoadFailed reason={byPurpose.failed.reason} />;

  const purposes = byPurpose.rows ?? [];
  const n = (v) => Number(v || 0);

  // COMPUTED FROM THE AGGREGATE, not from the 500 rows the record read: the
  // record is capped and the aggregate is not, so adding up the rows on screen
  // would quietly report "the last 500 calls" as "all calls".
  const billed = purposes.reduce((t, p) => t + n(p.billed), 0);
  const calls = purposes.reduce((t, p) => t + n(p.calls), 0);
  const unknown = purposes.reduce((t, p) => t + n(p.cost_unknown), 0);
  const tokens = purposes.reduce(
    (t, p) => t + n(p.prompt_tokens) + n(p.completion_tokens), 0);
  const used = purposes.filter((p) => n(p.calls) > 0).length;

  return (
    <div data-testid="ai-use">
      <div className="sheet-head">
        <h1 className="sheet-title">AI use</h1>
        <span className="sheet-note">
          {used} of {purposes.length} declared purposes have ever been used
        </span>
      </div>
      <div className="font-serif italic mt-2" style={{ fontSize: 14, color: 'var(--mute)' }}>
        Every question this system has put to a model, and what came back —
        including the times nothing did.
      </div>

      <div className="mt-5 grid gap-3"
           style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(170px, 1fr))' }}>
        <StatBox label="questions asked" n={calls} />
        {/* BILLED IS THE SPEND FIGURE, and it is deliberately the one given a
            label rather than "calls". The two differ by every call the doorway
            declined to make. */}
        <StatBox label="of those, billed" n={billed} />
        <StatBox label="tokens reported" n={tokens} />
        <StatBox label="billed, cost not reported" n={unknown} />
      </div>

      {/* THE CAVEAT SITS BESIDE THE NUMBER, not in a footnote. A reader who
          takes the token figure for the whole bill is the one way this screen
          misleads. */}
      {unknown > 0 && (
        <div className="caption mt-3" data-testid="cost-caveat" style={{ lineHeight: 1.7 }}>
          The token figure is <strong>at least</strong> that, not exactly that:{' '}
          {unknown} billed {unknown === 1 ? 'call' : 'calls'} came back with no
          usage reported by the provider, and those are recorded as unknown
          rather than as nothing.
        </div>
      )}

      {calls === 0 && (
        <div className="panel p-4 mt-6" data-testid="never-asked">
          <PanelHead
            title="Nothing has been asked of a model"
            sub="Either no model is configured, or every AI feature is switched off for this company. Both are ordinary states, and neither is an error." />
        </div>
      )}

      <div className="panel p-4 mt-6" data-testid="by-purpose">
        <PanelHead
          title="What it has been asked to do"
          sub="Every purpose the schema declares, including the ones nobody has used — a capability switched off, or never taken up, is usually the row somebody came here to find." />
        <table className="table mt-3">
          <thead>
            <tr>
              <th>purpose</th><th>asked</th><th>answered</th><th>absent</th>
              <th>never asked</th><th>billed</th><th>tokens</th><th>last</th>
            </tr>
          </thead>
          <tbody>
            {purposes.map((p) => (
              <tr key={p.purpose} data-testid="purpose-row">
                <td className="font-mono">{p.purpose}</td>
                <td className="font-mono">{n(p.calls)}</td>
                <td className="font-mono">{n(p.answered)}</td>
                <td className="font-mono">{n(p.absent)}</td>
                <td className="font-mono">{n(p.not_asked)}</td>
                <td className="font-mono">{n(p.billed)}</td>
                <td className="font-mono">
                  {n(p.prompt_tokens) + n(p.completion_tokens)}
                  {n(p.cost_unknown) > 0 && (
                    <span className="caption"> +{n(p.cost_unknown)} unknown</span>
                  )}
                </td>
                {/* NOT DRAWN AS A BLANK. An empty cell reads as "no data";
                    this says which of the two it is. */}
                <td className="caption">
                  {p.last_called_at
                    ? new Date(p.last_called_at).toLocaleDateString()
                    : 'never used'}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* WHAT THE PER-CONTRACT INDEX COST TWICE (0114). Drawn only when there
          is something to draw: an empty table here would suggest a cost was
          measured and found to be nought, when the honest reading of no rows
          is that no wording was read more than once.

          THE READING IS PER CONTRACT ON PURPOSE — that is what lets disposal
          reach a contract's readings and lets "seven of nine contracts are
          indexed" be true — so this is a cost somebody chose, not a defect.
          It is here so they can see the size of what they chose. */}
      {reuse.status === 'loaded' && reuse.rows.length > 0 && (
        <div className="panel p-4 mt-6" data-testid="paragraph-reuse">
          <PanelHead
            title="Wording read more than once"
            sub="The paragraph index is kept per contract, so the same approved clause is read again for every contract that issued it. That is what lets a disposal reach a contract’s readings and a coverage count be honest per contract — and it is paid for out of the paragraph allowance." />
          <table className="table mt-3">
            <thead>
              <tr>
                <th>clause</th><th>contracts</th><th>rows indexed</th>
                <th>readings taken</th>
              </tr>
            </thead>
            <tbody>
              {reuse.rows.map((r) => (
                <tr key={r.text_sha256} data-testid="reuse-row">
                  <td className="font-mono">{r.example_clause}</td>
                  <td className="font-mono">{n(r.contracts)}</td>
                  <td className="font-mono">{n(r.rows_indexed)}</td>
                  <td className="font-mono">{n(r.readings_taken)}</td>
                </tr>
              ))}
            </tbody>
          </table>
          <div className="caption mt-2">
            The 200 most-repeated are shown.
          </div>
        </div>
      )}

      <div className="panel p-4 mt-6" data-testid="the-calls">
        <PanelHead
          title="The calls themselves"
          sub="Newest first, and capped — the figures above are computed over the whole record, not over what is drawn here." />
        <ListFilter filter={filter} testid="ai-use"
                    placeholder="purpose, person, model or outcome"
                    facetLabel="every outcome" />
        <table className="table mt-3">
          <thead>
            <tr>
              <th>when</th><th>purpose</th><th>who caused it</th><th>model</th>
              <th>outcome</th><th>tokens</th>
            </tr>
          </thead>
          <tbody>
            {filter.shown.map((r) => (
              <tr key={r.call_id} data-testid="call-row">
                <td className="caption">
                  {new Date(r.called_at).toLocaleString()}
                </td>
                <td className="font-mono">{r.purpose}</td>
                <td className="font-mono">{r.actor}</td>
                <td className="font-mono">
                  {r.model}
                  {r.model_version ? <span className="caption"> {r.model_version}</span> : null}
                </td>
                <td>
                  {/* THE STORED WORD, and the badge says whether it was a bill.
                      An absence is not an error — the provider did the work and
                      nothing usable came back, which is a fact worth seeing. */}
                  <span className={r.outcome === 'answered' ? 'stamp stamp-decided'
                                   : r.outcome === 'absent' ? 'stamp stamp-pending'
                                   : 'stamp'}
                        style={{ '--rot': '-0.7deg' }}>
                    {r.outcome === 'not_asked' ? 'never asked' : r.outcome}
                  </span>
                  {r.absent_reason && (
                    <div className="caption mt-1" style={{ maxWidth: 380 }}>
                      {r.absent_reason}
                    </div>
                  )}
                </td>
                <td className="font-mono">
                  {r.total_tokens === null || r.total_tokens === undefined
                    ? <span className="caption">{r.billed ? 'not reported' : '—'}</span>
                    : n(r.total_tokens)}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {filter.shown.length === 0 && (
          <div className="caption mt-3">
            No calls match. The record itself may also be empty — the figures
            above say which.
          </div>
        )}
      </div>
    </div>
  );
}
