/* claude-draft.jsx — live first-pass estimate via window.claude.complete (backed by the local
   /api/complete proxy → real Anthropic Messages API). Returns a normalised draft object.
   Falls back to SAMPLE_DRAFTS on any failure.

   The prompt is split so the rate card can be prompt-cached: the instructions + rate card go in
   `system` (stable prefix; the rate-card block is marked cache_control), and the per-RFQ brief
   goes in `messages`. extractJSON + normaliseDraft live in assets/js/draft-normalise.js so the
   brittle parsing is unit-tested headlessly. */

// System prompt: stable across RFQs. Block 2 (the rate card) is cache-control'd so forks with a
// large real price list get prompt caching for free. (The sample rate card is below Opus's
// ~4096-token cache minimum, so caching is a no-op until the card grows — wired correctly regardless.)
window.buildDraftSystem = function () {
  return [
    {
      type: 'text',
      text: [
        'You are an estimating assistant for an Australian CNC / fabrication shop.',
        'Read the inbound RFQ and produce a FIRST-PASS, line-item cost build-up that a human estimator will review and own.',
        'Use the rate card for pricing. Where the RFQ is silent, make a sensible assumption AND raise a clarifying question — never hide an assumption.',
        'Lower the confidence (0-100) on any line that depends on an assumption or an ambiguous spec.'
      ].join('\n')
    },
    {
      type: 'text',
      text: '=== RATE CARD (your data) ===\n' + window.RATE_CARD,
      cache_control: { type: 'ephemeral' }
    }
  ];
};

// User message: the specific RFQ + the exact output contract.
window.buildDraftUser = function (rfq) {
  return [
    '=== INBOUND RFQ ===',
    'From: ' + rfq.co + ' <' + rfq.email + '>',
    'Subject: ' + rfq.subject,
    '',
    rfq.body,
    '',
    '=== OUTPUT ===',
    'Return ONLY valid minified JSON, no prose, no markdown fences, matching exactly:',
    '{"part":string,"material":{"spec":string,"cost":number,"source_ref":string,"confidence":number},' +
    '"line_items":[{"op":string,"qty":number,"unit_rate":number,"source_ref":string,"confidence":number}],' +
    '"setup":number,"lead_time_days":number,"base_qty":number,"overall_confidence":number,' +
    '"assumptions":[string],"clarifying_questions":[{"q":string,"assumption":string}]}',
    'Rules: 4-7 line_items. unit_rate is the per-PART rate for that op. ' +
    'qty is the PER-PART operation count, NEVER multiplied by the batch — e.g. a part with 4× Ø6.0 holes is qty:4 (NOT 4×50=200); facing once per part is qty:1. ' +
    'base_qty = the total quantity of parts requested. source_ref cites the RFQ line or drawing feature it came from (short). Keep every string concise.'
  ].join('\n');
};

// draftQuote(rfq, rfqBodyOverride) -> { draft, live: bool, error: string|null }
window.draftQuote = async function (rfq, bodyOverride) {
  const effective = bodyOverride !== undefined ? { ...rfq, body: bodyOverride } : rfq;
  const fallback = window.SAMPLE_DRAFTS[rfq.id] || null;
  const { extractJSON, normaliseDraft } = window.RFQNormalise;

  if (!window.claude || !window.claude.complete) {
    return { draft: fallback, live: false, error: 'offline' };
  }
  try {
    // A canonical RFQ (no body override) sends its id → served canned (0 tokens).
    // A pasted/edited brief omits the id → live.
    const text = await window.claude.complete({
      system: window.buildDraftSystem(),
      messages: [{ role: 'user', content: window.buildDraftUser(effective) }],
      scenarioId: bodyOverride !== undefined ? undefined : rfq.id
    });
    const parsed = normaliseDraft(extractJSON(text), effective);
    if (parsed && parsed.line_items.length) return { draft: parsed, live: true, error: null };
    return { draft: fallback, live: false, error: 'parse' };
  } catch (e) {
    return { draft: fallback, live: false, error: String(e && e.message || e) };
  }
};
