// Brook Consultancy — AI analysis engine

const BROOK_SYSTEM_PROMPT = `You are an experienced business management consultant conducting a comprehensive operational review on behalf of Brook Consultancy Partners. Analyze the meeting transcript and/or summary below. Extract evidence ONLY from what is actually documented — do NOT invent facts. Where there is no evidence, return an empty array — never make assumptions.

You will produce findings against these EVALUATION AREAS (each has indicators):

  AREA: Leadership & Strategy
  (grade scale: "exceptional", "strong", "adequate", "needs_improvement", "critical")
    - id="ls_vision" — Strategic Vision: Clear, documented strategic direction understood and embraced across the organisation
    - id="ls_goals" — Goal Setting & KPIs: SMART objectives set with measurable KPIs and regular progress tracking
    - id="ls_decision" — Decision Making: Timely, evidence-based decisions with clear accountability and communication
    - id="ls_change" — Change Management: Structured approach to implementing and embedding organisational change

  AREA: Operations & Processes
  (grade scale: "exceptional", "strong", "adequate", "needs_improvement", "critical")
    - id="op_efficiency" — Operational Efficiency: Streamlined processes that minimise waste and maximise productivity
    - id="op_quality" — Quality Management: Consistent quality standards with monitoring, review and continuous improvement
    - id="op_documentation" — Process Documentation: Procedures documented, accessible, current and followed in practice
    - id="op_compliance" — Compliance & Controls: Internal controls effective; regulatory and legal requirements met

  AREA: Financial Management
  (grade scale: "exceptional", "strong", "adequate", "needs_improvement", "critical")
    - id="fm_planning" — Financial Planning: Realistic budgets, forecasts and cash flow management
    - id="fm_reporting" — Financial Reporting: Accurate, timely reports that inform decision-making
    - id="fm_controls" — Financial Controls: Segregation of duties, authorisation levels, audit trails in place
    - id="fm_performance" — Financial Performance: Revenue, margins and cost management meet targets

  AREA: People & Culture
  (grade scale: "exceptional", "strong", "adequate", "needs_improvement", "critical")
    - id="pc_talent" — Talent Management: Effective recruitment, onboarding, development and retention strategies
    - id="pc_performance" — Performance Management: Clear expectations, regular feedback, and documented reviews
    - id="pc_culture" — Organisational Culture: Positive, inclusive culture with high engagement and morale
    - id="pc_capacity" — Capacity & Workload: Adequate staffing levels with manageable, sustainable workloads

  AREA: Risk & Governance
  (grade scale: "exceptional", "strong", "adequate", "needs_improvement", "critical")
    - id="rg_identification" — Risk Identification: Systematic identification and assessment of business risks
    - id="rg_mitigation" — Risk Mitigation: Controls and contingency plans proportionate to risks
    - id="rg_governance" — Governance Structure: Clear roles, responsibilities and reporting lines; board and leadership oversight
    - id="rg_ethics" — Ethics & Integrity: Code of conduct, whistleblowing procedures, ethical business practices

  AREA: Customer & Stakeholder Management
  (grade scale: "exceptional", "strong", "adequate", "needs_improvement", "critical")
    - id="cs_satisfaction" — Customer Satisfaction: Systems to gather, analyse and act on customer feedback
    - id="cs_relationships" — Stakeholder Relationships: Strong relationships with key partners, suppliers, investors
    - id="cs_communication" — Communication: Clear, consistent messaging to internal and external stakeholders
    - id="cs_value" — Value Delivery: Products and services consistently meet or exceed customer expectations

  AREA: Technology & Innovation
  (grade scale: "exceptional", "strong", "adequate", "needs_improvement", "critical")
    - id="ti_systems" — Technology Systems: Fit-for-purpose systems that support business operations effectively
    - id="ti_data" — Data Management: Data accurate, secure, accessible and used to drive decisions
    - id="ti_innovation" — Innovation & Improvement: Culture of continuous improvement with idea generation and testing
    - id="ti_digital" — Digital Maturity: Appropriate use of digital tools and automation to enhance efficiency

You will also identify BUSINESS COMPLIANCE & BEST PRACTICE findings:

  Section: Legal & Regulatory
    - id="lr_registration" — Business registration and licences current and displayed where required
    - id="lr_insurance" — Appropriate insurance coverage (liability, professional indemnity, etc.) current
    - id="lr_contracts" — Customer and supplier contracts documented with clear terms
    - id="lr_ip" — Intellectual property protected (trademarks, patents, copyrights as applicable)
    - id="lr_data_protection" — GDPR and data protection compliance (privacy policy, consent, data security)
    - id="lr_employment" — Employment law compliance (contracts, right to work, health and safety)

  Section: Financial Controls
    - id="fc_accounts" — Annual accounts filed on time; tax returns submitted
    - id="fc_reconciliation" — Regular bank reconciliations performed and reviewed
    - id="fc_authorization" — Spending authorisation limits defined and followed
    - id="fc_segregation" — Segregation of duties in financial processes
    - id="fc_audit_trail" — Complete audit trail for all transactions

  Section: Records & Documentation
    - id="rd_policies" — Core policies documented (HR, H&S, data protection, complaints, etc.)
    - id="rd_records" — Business records retained per legal requirements (7 years financial, etc.)
    - id="rd_meetings" — Leadership meetings documented with decisions recorded
    - id="rd_contracts_filed" — Contracts and agreements filed and accessible

  Section: Health, Safety & Premises
    - id="hs_risk_assessment" — Workplace risk assessments completed and reviewed
    - id="hs_training" — H&S training provided to all staff; records maintained
    - id="hs_accidents" — Accident and incident reporting system in place; RIDDOR compliance
    - id="hs_fire" — Fire risk assessment, equipment serviced, drills logged
    - id="hs_first_aid" — Adequate first aid provision and trained first aiders

  Section: Information Security
    - id="is_backup" — Regular data backups with tested restore procedures
    - id="is_access" — Access controls and password policies enforced
    - id="is_cyber" — Cybersecurity measures (firewall, antivirus, encryption) appropriate
    - id="is_breach" — Data breach response plan documented

You will also draft headline FINDINGS: strengths, areas for development, and an action plan.

==========
MEETING SUMMARY:
{{SUMMARY}}

MEETING TRANSCRIPT / DOCUMENT:
{{TRANSCRIPT}}
==========

Return a SINGLE JSON object in EXACTLY the schema below. Do not wrap in markdown. Do not add commentary before or after.

{
  "areas": {
    "<area-id>": {
      "indicators": [
        {
          "id": "<indicator id>",
          "evidence": ["<specific quote or fact from document>"],
          "confidence": "high|med|low"
        }
      ],
      "judgement": "<2-4 sentence narrative assessment>",
      "suggestedGrade": "<grade id from that area's scale, or 'insufficient_evidence'>",
      "gradeReasoning": "<one sentence explaining the grade>"
    }
  },
  "compliance": {
    "findings": [
      { "id": "<compliance item id>", "status": "compliant|partial|non_compliant|na", "note": "<short evidence note from document>" }
    ]
  },
  "findings": {
    "strengths": ["<3-6 specific strengths with evidence>"],
    "areas_for_development": ["<3-6 specific development areas>"],
    "actions": [
      { "action": "<specific, actionable task>", "owner": "<role e.g. CEO / Finance Director>", "priority": "Critical|High|Medium|Low", "timeline": "<suggested completion timeframe>" }
    ]
  },
  "executive_summary": {
    "overall_assessment": "<2-3 sentence high-level summary>",
    "key_risks": ["<top 3-5 risks identified>"],
    "immediate_priorities": ["<top 3-5 actions needed urgently>"]
  },
  "consultation_autofill": {
    "organisation_overview": "<narrative paragraph>",
    "client_request": "<what the client is asking for>",
    "support_type": ["<tags from support type list>"],
    "stated_priorities": "<client priorities in their words>",
    "core_challenges": "<narrative summary of challenges>",
    "challenge_tags": ["<tags from challenge tag list>"],
    "urgency": "Critical|High|Moderate|Low",
    "trigger": "<what prompted them to seek support>",
    "previous_attempts": "<what has been tried before>",
    "regulatory_status": "<regulatory body and current standing>",
    "safeguarding_status": "<safeguarding arrangements summary>",
    "policy_status": "<documentation and policy state>",
    "finance_systems": ["<system tags>"],
    "hr_systems": ["<system tags>"],
    "operational_systems": "<narrative>",
    "data_maturity": "Strong|Moderate|Weak|Very limited",
    "financial_overview": "<narrative financial summary>",
    "budget_range": "<budget bracket>",
    "financial_position": "<position dropdown value>",
    "income_sources": ["<income type tags>"],
    "cost_pressures": "<narrative>",
    "workforce_summary": "<people and culture narrative>",
    "short_term_priorities": "<6-12 month goals>",
    "long_term_vision": "<3-5 year ambition>",
    "partnership_expectations": "<what they want from Brook>",
    "budget_for_support": "<budget bracket>",
    "timeline_to_start": "<timeline dropdown value>",
    "situation_narrative": {
      "paragraph_1": "<who the organisation is and context>",
      "paragraph_2": "<core challenges and how they developed>",
      "paragraph_3": "<what the client is asking for>",
      "paragraph_4": "<professional assessment of real need>"
    },
    "key_quotes": [
      { "quote": "<verbatim or near-verbatim quote>", "context": "<what prompted this>", "tag": "<relevant section>" }
    ],
    "baseline_metrics": {
      "annual_budget": "<value if mentioned>",
      "financial_position_detail": "<surplus/deficit detail>",
      "staff_count": "<number if mentioned>",
      "service_users": "<number if mentioned>",
      "sites": "<number if mentioned>",
      "regulatory_rating": "<rating and date if mentioned>",
      "last_inspection_date": "<date if mentioned>",
      "staff_vacancy_detail": "<detail if mentioned>",
      "staff_turnover": "<detail if mentioned>",
      "other_metrics": "<any other figures mentioned>"
    },
    "recommended_services": ["<service tags>"],
    "proposed_workstreams": [
      { "title": "<workstream title>", "description": "<what this involves>", "timeframe": "<estimated timeframe>", "priority": "Immediate|Phase 2|Phase 3" }
    ],
    "overall_impression": "<consultant-facing assessment>",
    "key_risks": ["<risks to the organisation>"],
    "brook_risk_level": "Low|Medium|High|Do Not Engage",
    "lead_priority": "Hot|Warm|Cool|Long-term|Not suitable",
    "recommended_next_steps": "<immediate next steps>",
    "success_definition": "<what success looks like>"
  }
}

Use these area IDs in the "areas" object: "leadership", "operations", "financial", "people", "risk", "customer", "technology"

CRITICAL RULES:
- Skip any area, indicator, or compliance item that has NO supporting evidence in the source document
- Better to omit than to invent
- Be specific and quote-like in evidence bullets so findings can be verified against source
- Confidence levels: high = direct evidence, med = reasonable inference, low = limited/indirect evidence
- Only include what can be substantiated from the actual content provided`;

// ---------------------------------------------------------------
// Map raw AI consultation_autofill -> Brook field IDs (fields)
// ---------------------------------------------------------------
function mapAutofillToFields(raw, summary, transcript) {
  if (!raw) return { fields: {}, repeaters: {}, dashboard: {} };

  const a = raw.consultation_autofill || {};
  const baseline = a.baseline_metrics || {};
  const narrative = a.situation_narrative || {};

  // Narrative-style fields
  const fields = {};

  const set = (id, value, conf = 'med') => {
    if (value === undefined || value === null) return;
    if (typeof value === 'string' && !value.trim()) return;
    if (Array.isArray(value) && value.length === 0) return;
    fields[id] = { value, confidence: conf };
  };

  // ---- Section 1
  set('history_notes', a.organisation_overview, 'high');

  // ---- Section 2
  set('client_request', a.client_request, 'high');
  set('support_type', a.support_type, 'med');
  set('stated_priorities', a.stated_priorities, 'high');

  // ---- Section 3
  set('trigger_notes', a.trigger, 'high');
  set('core_challenges', a.core_challenges, 'high');
  set('challenge_tags', a.challenge_tags, 'med');
  set('urgency', a.urgency, 'med');
  set('previous_attempts', a.previous_attempts, 'med');

  // ---- Section 4
  set('regulatory_notes', a.regulatory_status, 'high');
  set('safeguarding_notes', a.safeguarding_status, 'med');
  set('policy_notes', a.policy_status, 'med');

  // Map regulatory_status to dropdown if it looks like one of the values
  const regStatusMap = ['Outstanding','Good','Requires Improvement','Inadequate','Monitoring','Under Enforcement','Not yet inspected','Not applicable'];
  if (typeof a.regulatory_status === 'string') {
    const found = regStatusMap.find(s => a.regulatory_status.toLowerCase().includes(s.toLowerCase()));
    if (found) set('regulatory_status', found, 'med');
  }

  // ---- Section 5
  set('finance_systems', a.finance_systems, 'med');
  set('hr_systems', a.hr_systems, 'med');
  set('operational_systems', a.operational_systems, 'med');
  // Map data_maturity to dropdown labels
  if (a.data_maturity) {
    const dm = a.data_maturity.toLowerCase();
    if (dm.startsWith('strong')) set('data_maturity', 'Strong — regular dashboards and data-driven decisions');
    else if (dm.startsWith('moderate')) set('data_maturity', 'Moderate — some reporting but inconsistent');
    else if (dm.startsWith('weak')) set('data_maturity', 'Weak — largely informal and reactive');
    else if (dm.startsWith('very')) set('data_maturity', 'Very limited — little to no data visibility');
  }

  // ---- Section 6
  set('financial_overview', a.financial_overview, 'high');
  set('budget_range', a.budget_range, 'med');
  set('financial_position', a.financial_position, 'med');
  set('income_sources', a.income_sources, 'med');
  set('cost_pressures', a.cost_pressures, 'med');

  // ---- Section 7 (workforce summary -> all 3 textareas — split if needed)
  if (a.workforce_summary) {
    set('workforce_notes', a.workforce_summary, 'med');
  }

  // ---- Section 8
  set('short_term_priorities', a.short_term_priorities, 'high');
  set('long_term_vision', a.long_term_vision, 'high');
  set('partnership_expectations', a.partnership_expectations, 'high');
  set('budget_for_support', a.budget_for_support, 'med');
  set('timeline_to_start', a.timeline_to_start, 'med');

  // ---- Section 9
  set('overall_impression', a.overall_impression, 'med');
  set('brook_risk_level', a.brook_risk_level, 'med');
  set('recommended_services', a.recommended_services, 'med');
  set('lead_priority', a.lead_priority, 'med');
  set('recommended_next_steps', a.recommended_next_steps, 'med');
  if (Array.isArray(a.key_risks) && a.key_risks.length) set('key_risks', a.key_risks.join('\n• '), 'high');

  // ---- Section 10 (baseline metrics + narrative)
  set('annual_budget', baseline.annual_budget, 'high');
  set('financial_position_detail', baseline.financial_position_detail, 'high');
  set('staff_count_detail', baseline.staff_count, 'high');
  set('service_users_detail', baseline.service_users, 'high');
  set('staff_vacancy_detail', baseline.staff_vacancy_detail, 'med');
  set('staff_turnover', baseline.staff_turnover, 'med');
  set('regulatory_rating', baseline.regulatory_rating, 'high');
  set('last_inspection_date', baseline.last_inspection_date, 'high');
  set('other_metrics', baseline.other_metrics, 'med');

  // Section 1 quick-capture numbers
  if (baseline.staff_count) set('staff_count', baseline.staff_count, 'high');
  if (baseline.service_users) set('service_users', baseline.service_users, 'high');
  if (baseline.sites) set('sites', baseline.sites, 'high');

  set('narrative_p1', narrative.paragraph_1, 'high');
  set('narrative_p2', narrative.paragraph_2, 'high');
  set('narrative_p3', narrative.paragraph_3, 'high');
  set('narrative_p4', narrative.paragraph_4, 'med');

  set('success_definition', a.success_definition, 'med');

  // Repeaters
  const repeaters = {};
  if (Array.isArray(a.key_quotes) && a.key_quotes.length) {
    repeaters.quotes = a.key_quotes.map(q => ({
      id: window.brookUid(),
      quote: q.quote || '',
      context: q.context || '',
      tag: q.tag || ''
    }));
  }
  if (Array.isArray(a.proposed_workstreams) && a.proposed_workstreams.length) {
    repeaters.workstreams = a.proposed_workstreams.map(w => ({
      id: window.brookUid(),
      title: w.title || '',
      description: w.description || '',
      timeframe: w.timeframe || '',
      priority: w.priority || ''
    }));
  }

  // aiResults — mirrors the Ofsted EYFS app's shape exactly:
  //   <areaId>: { indicators[], judgement, suggestedGrade, gradeReasoning }
  //   statutory: { findings: [{id, status, note}] }
  //   findings: { strengths, afd, actions }
  //   executive_summary: { overall_assessment, key_risks, immediate_priorities }
  const aiResults = {};
  Object.entries(raw.areas || {}).forEach(([k, v]) => {
    aiResults[k] = {
      indicators: v.indicators || [],
      judgement: v.judgement || '',
      suggestedGrade: v.suggestedGrade || 'insufficient_evidence',
      gradeReasoning: v.gradeReasoning || ''
    };
  });
  aiResults.statutory = { findings: (raw.compliance && raw.compliance.findings) || [] };
  aiResults.findings = {
    strengths: (raw.findings && raw.findings.strengths) || [],
    afd: (raw.findings && (raw.findings.areas_for_development || raw.findings.afd)) || [],
    actions: (raw.findings && raw.findings.actions) || []
  };
  aiResults.executive_summary = raw.executive_summary || { overall_assessment: '', key_risks: [], immediate_priorities: [] };

  return { fields, repeaters, aiResults };
}

// ---------------------------------------------------------------
// Run analysis via window.claude
// ---------------------------------------------------------------
async function runBrookAnalysis(summary, transcript, onStage) {
  if (!summary && !transcript) throw new Error('Please paste a meeting summary or transcript before running analysis.');

  onStage && onStage('preparing');

  const prompt = BROOK_SYSTEM_PROMPT
    .replace('{{SUMMARY}}', summary || '(no summary provided)')
    .replace('{{TRANSCRIPT}}', transcript || '(no full transcript provided)');

  onStage && onStage('analysing');

  let raw;
  try {
    raw = await window.claude.complete(prompt);
  } catch (e) {
    throw new Error('AI analysis failed: ' + (e.message || e));
  }

  onStage && onStage('parsing');

  // Parse JSON — try to find the JSON object even if wrapped
  let parsed;
  try {
    parsed = JSON.parse(raw);
  } catch {
    // try extracting first {...} block
    const match = raw.match(/\{[\s\S]*\}/);
    if (!match) throw new Error('AI returned malformed response. Please try again.');
    try { parsed = JSON.parse(match[0]); }
    catch (e) { throw new Error('Could not parse AI response as JSON.'); }
  }

  onStage && onStage('mapping');

  const mapped = mapAutofillToFields(parsed, summary, transcript);
  return { raw: parsed, mapped };
}

// ---------------------------------------------------------------
// Demo transcript for testing
// ---------------------------------------------------------------
const BROOK_DEMO_TRANSCRIPT = `MEETING SUMMARY — Initial Discovery Call
Organisation: Westbrook Care Home
Attendees: Sarah Mitchell (CEO/Owner), David Chen (Brook Consultancy)
Date: 2024-04-15
Duration: 52 minutes

Executive Summary:
Sarah Mitchell, owner-operator of Westbrook Care Home, a 38-bed residential care home in the Greater Manchester area, reached out to Brook Consultancy following a CQC inspection in February 2024 that downgraded the home from "Good" to "Requires Improvement". The inspection raised concerns about leadership, medication administration, and care plan documentation. Sarah is the founder and has run the home for 17 years, but has lost two senior managers in the last six months and her registered manager is on long-term sick leave. The home operates with approximately 65 staff across full-time, part-time and agency. Annual turnover is approximately £2.4M with a current operating deficit of £85,000 building over the last 9 months, primarily driven by agency staffing costs and Local Authority fee pressures. Sarah has no clear successor and has been working 70+ hour weeks. She is asking for help with regulatory recovery, financial stabilisation, and identifying an interim registered manager. Budget for support: £25-50k. Wants to start within a month.

TRANSCRIPT EXCERPTS:

Sarah: "Honestly David, I'm exhausted. I've been doing this for 17 years and I've never felt this overwhelmed. The CQC report was a gut punch — we've always been Good, sometimes Outstanding in caring. To be told we're Requires Improvement was devastating."

David: "Tell me about your leadership team right now."

Sarah: "That's part of the problem. My registered manager Janet has been off with stress since January. My deputy left in November — she went to a competitor. My head of care left in February right after the inspection — I think she felt she'd let me down. I'm essentially the registered manager, the deputy, and the operations lead. There's no governing body, it's just me and my accountant for the financial side."

David: "Have you been able to recruit replacements?"

Sarah: "I've been trying. The market is brutal. I've had agency cover for three months which is killing my margins. We're spending about £18k a month on agency that I shouldn't be."

David: "What's the financial picture?"

Sarah: "We turn over about £2.4 million. Right now I'm £85k in deficit on a year-to-date basis. Cash reserves are about three months. I use Sage for the accounts but I'm not getting management accounts regularly — my accountant is good but reactive. I haven't had a proper finance review in two years. Local Authority fees haven't kept pace with cost increases — we have 28 LA-funded residents and 10 self-funders."

David: "What about your regulatory work?"

Sarah: "The CQC action plan is due in 6 weeks. I'm meant to be evidencing improvements in medication management, person-centred care plans, and governance. Honestly, I'm drowning. My policies haven't been reviewed in 18 months. I have a safeguarding lead but she's also one of the people doing extra shifts."

David: "If we could fix one thing, what would it be?"

Sarah: "Get me a competent interim registered manager who can lead the CQC recovery. That's the single most pressing thing. Then help me get my finances under control. I can't keep losing this kind of money."

David: "What does success look like at the end of our engagement?"

Sarah: "CQC back to Good within 12 months. Operating to break-even. A permanent senior team I can trust. And me working 50 hours not 70."

David: "Have you tried external support before?"

Sarah: "Years ago I had a CQC consultant who was useless — gave me a generic plan. I've never had financial support. My accountant does the books, that's it."

David: "Any other risks I should be aware of?"

Sarah: "Two of my LA contracts are out for re-tender in September. If I lose either I'm in real trouble. And my insurance renewal is in July — premiums going up I'm told. We had one safeguarding referral in March — investigated and closed, no concerns substantiated, but it's on my mind."

David: "Have you ever had an audit of your safer recruitment processes?"

Sarah: "No. We do DBS, references, right to work — but I've not had it audited."

David: "Last question — who else has been involved in the decision to call us?"

Sarah: "It's mine. My husband knows obviously. I haven't told the staff yet. I will once we have a plan."`;

Object.assign(window, {
  BROOK_SYSTEM_PROMPT,
  BROOK_DEMO_TRANSCRIPT,
  runBrookAnalysis,
  mapAutofillToFields
});
