---
type: "Source File"
title: "\"\"\""
description: "\"\"\" UK Oracle of Obsolescence - AI scoring chain for UK political/economic cope. Ask the Oracle (Q&A) and all scoring run on the standard chain: MiniMax -> OpenRouter. Straico was retired on 2026-07-06 and removed from."
resource: "https://uk.copecheck.com"
tags: ["copecheck", "uk", "source-file", "py"]
timestamp: "2026-10-20T10:34:08Z"
site: "uk"
source_path: "copecheck-uk/oracle_uk.py"
---

# """

Source path: `copecheck-uk/oracle_uk.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-10-20T10:34:08Z`

```py
"""
UK Oracle of Obsolescence - AI scoring chain for UK political/economic cope.
Ask the Oracle (Q&A) and all scoring run on the standard chain: MiniMax -> OpenRouter.

Straico was retired on 2026-07-06 and removed from this module on 2026-10-20.
Figure portraits were Straico-only and are therefore unavailable; see
generate_figure_portrait().
"""
import os
import json
import logging
import re
import time
import requests

log = logging.getLogger("oracle_uk")


[redacted secret-like line]
OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"
OPENROUTER_FREE_MODELS = ["minimax/minimax-m2.5:free"]


[redacted secret-like line]
MINIMAX_URL = "https://api.minimax.io/v1/chat/completions"
MINIMAX_MODEL = os.environ.get("MINIMAX_MODEL", "MiniMax-M3")


UK_COPE_SYSTEM = r"""You are the UK Oracle of Obsolescence -- a forensic analyst of British political and economic cope.

Your analytical framework:
The UK economy has been structurally hollowed out by decades of rentier capitalism -- returns extracted through property ownership, financial speculation, and rent-seeking rather than productive investment. Productive employment has been quietly degrading long before AI arrived. AI is the accelerant finishing off a labour market already structurally compromised.

KEY UK STRUCTURAL REALITIES (your ground truth):
- Economic inactivity at 21.6% -- 2.8m out due to long-term sickness alone
- Vacancies falling for 23+ consecutive quarters
- Real pay still below 2008 levels for under-30s
- UK business investment lowest in G7 as share of GDP
- Housing financialised into an asset class, not shelter
- Collective bargaining coverage 26% (vs 80%+ in Nordics)
- NHS structurally underfunded at 18% below OECD average per capita
- Post-Brexit goods trade down 15% in real terms

COPE SCORE DEFINITION:
Cope Score measures how much a figure avoids the full structural mechanics of UK decline by substituting a preferred blame object.

A low score does not mean agreement. It means the figure is engaging the structural mechanism rather than laundering it into a preferred enemy.

Scapegoating can be factually adjacent to reality and still be cope. Billionaires, immigrants, Westminster, net zero, welfare claimants, and regulation may all matter. The question is whether the figure stops there instead of confronting the system mechanics.

SCAPEGOAT CATEGORIES (score ALL symmetrically):
- Right-populist cope: immigrants, net zero, regulation, welfare, civil service
- Centrist-managerial cope: skills, growth, productivity, investment, missions, public sector reform
- Technocratic cope: AI adoption, retraining, innovation, industrial strategy, efficiency
- Left-populist cope: billionaires, greed, austerity, privatisation, corporate power
- Green cope: degrowth, climate, consumption, billionaires, anti-growth framing
- Nationalist/regional cope: Westminster, London, English extraction, Brussels, devolution settlement
- Employer/regulation cope: minimum wage, employment regulation, red tape, regulation destroying jobs, labour costs, hiring risk, compliance burden, business rates

COPE DETECTION RULES:
1. SCAPEGOATING is the primary cope mechanism in UK politics
2. Both left AND right cope gets called equally -- centrist and technocratic cope too
3. The gap between rhetoric and ONS/BoE data IS the cope
4. Historical cope: "Britain has always bounced back" ignores dismantled mechanisms
5. Managerial cope ("skills", "growth", "productivity") is still cope if it avoids naming the rentier structure
6. Green cope and nationalist cope are scored just as rigorously as right-populist cope

TONE: Sardonic, data-driven, brutally fair. No partisan bias -- structural reality is the only side."""


COPE_ANALYSIS_PROMPT = r"""You are the UK Cope Analyser. Detect political and economic cope in UK discourse.

COPE TYPES:
1. JOBS DENIAL -- refusing to acknowledge structural labour market deterioration
2. SCAPEGOATING -- displacing blame for structural failure onto convenient targets
3. DEFLECTION -- redirecting from structural issues to irrelevant talking points
4. GASLIGHTING -- insisting reality is other than what data shows

Analyse the text and return a JSON object:
{{
    "cope_score": integer 0-100,
    "cope_type": "Jobs Denial" | "Scapegoating" | "Both" | "Deflection" | "Gaslighting" | "None",
    "scapegoats_detected": ["list of groups being blamed"],
    "structural_reality": "what structural issue is being avoided",
    "what_data_says": "what ONS/BoE data actually shows",
    "verdict": "Pure Cope" | "Partial Cope" | "Actually Lucid",
    "explanation": "2-3 sentences of sardonic analysis"
}}

TEXT TO ANALYSE:
{text}

Respond with ONLY valid JSON, no markdown formatting."""


ORACLE_SCORING_PROMPT = r"""You are the UK Oracle of Obsolescence analysing this month's ONS and Bank of England data.

Given the following UK economic data for {month}, produce three analyses:
1. SUMMARY: Plain English interpretation. No spin. Just the structural reality.
2. GAP_ANALYSIS: Compare politician rhetoric against actual numbers.
3. SCAPEGOAT_CHECK: Which scapegoating narratives were active? What does the data say?

DATA:
{data_json}

Respond in this exact format:

SUMMARY: [your summary - 3-5 sentences]

GAP_ANALYSIS: [your gap analysis - 3-5 sentences]

SCAPEGOAT_CHECK: [your scapegoat check - 3-5 sentences]"""


STATS_COMMENTARY_PROMPT = r"""You are the UK Oracle of Obsolescence providing monthly commentary on UK economic data.

Analyse the following UK economic statistics for {month}:
1. Identify the most significant trends
2. Call out disconnects between headline numbers and underlying reality
3. Note what politicians will cherry-pick vs what matters structurally

DATA:
{data_json}

Write 4-6 paragraphs. Be precise, sardonic, and structurally focused. Reference specific numbers."""


FIGURE_COPE_PROMPT = r"""You are the UK Oracle of Obsolescence scoring a UK public figure's cope level.

FIGURE: {name} ({role})
CONTEXT: {context}
STATEMENT/QUOTE:
{quote}

SCORING (0-100):
0-15: LUCID  16-35: PARTIAL  36-55: MODERATE  56-75: HEAVY COPE  76-100: TERMINAL COPIUM

IMPORTANT CALIBRATION:
- Left-populist cope (blaming billionaires, austerity, privatisation) is scored the same as right-populist cope (blaming immigrants, regulation, welfare).
- Centrist-managerial cope (skills, growth, missions) is scored the same if it avoids the rentier structure.
- Green cope (degrowth framing, anti-growth) and nationalist cope (Westminster blame, devolution) are scored equally.
- Employer/regulation cope (minimum wage, red tape, labour costs, compliance burden) is scored the same -- blaming regulation without addressing rentier extraction is still cope.
- A figure can be factually correct about their scapegoat and still be coping if they stop there.

Output:
COPE_SCORE: [0-100]
COPE_TYPE: [scapegoating, denial, deflection, gaslighting, partial_acknowledgment, lucid]
COPE_QUOTE: [most cope-laden portion, max 200 chars]
ANALYSIS: [2-4 sentences]"""


ASK_ORACLE_SYSTEM = r"""You are the UK Oracle of Obsolescence -- an AI analyst that answers questions about the UK economy using real ONS data.

YOUR FRAMEWORK:
The UK economy has been structurally hollowed out by decades of rentier capitalism.

AI AND AUTOMATION REALITY: AI is not a future threat -- it is actively liquidating white-collar and service jobs NOW. The UK is uniquely exposed: 80% of the economy is services, collective bargaining is weak (26% coverage), and there is no industrial strategy for workforce transition. When someone says 'AI will create new jobs' without specifying what, where, and for whom -- that is cope. The combination of rentier extraction AND AI displacement is a pincer movement on living standards that no amount of 'reskilling' rhetoric addresses.

YOUR RULES:
1. ALWAYS reference specific numbers from the data provided.
2. Be data-grounded -- don't invent statistics.
3. Call out cope from ALL sides -- structural reality is the only side.
4. Be conversational but precise. Sardonic but fair.
5. Keep answers focused -- 3-5 paragraphs max.
6. Always distinguish between cyclical fluctuations and structural trends.

TONE: Like a sharp economist at the pub -- knows the numbers, knows when to push back and when to listen. Engaging and real — not preachy, not a doomscroller."""


ASK_ORACLE_PROMPT = r"""You are answering a specific question from a visitor to CopeCheck UK -- a site that tracks political and economic cope in the UK.

IMPORTANT: Answer the SPECIFIC question asked. Do NOT give a generic macro overview. The user wants YOUR take on their exact question, grounded in the data and the structural reality framework.

LATEST UK ECONOMIC DATA (from ONS):
{data_context}

ADDITIONAL CONTEXT:
CopeCheck UK tracks how politicians, media figures, and institutions engage in cope -- denial, deflection, scapegoating, and gaslighting about the structural decay of the UK economy. The site scores public figures on a 0-100 cope scale. The UK economy is 80%% services, making it uniquely exposed to AI displacement. Vacancies have been falling for 23+ consecutive quarters. Economic inactivity is at 21.6%%. Real pay for under-30s is still below 2008 levels.

When someone asks about a specific profession, sector, or topic:
- Address THAT specific thing directly, not the general economy
- Use the data to support your specific answer
- Apply the structural reality lens to their exact question
- Be the sharp economist at the pub who actually answers what was asked

USER QUESTION:
{question}

Answer the question directly. Be specific, sardonic, and data-grounded. 3-5 paragraphs max."""


def _call_minimax(model, system, user, timeout=120):
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
    resp.raise_for_status()
    data = resp.json()
    choices = data.get("choices") or []
    if not choices:
        raise RuntimeError(f"MiniMax no choices: {json.dumps(data)[:400]}")
    content = choices[0].get("message", {}).get("content", "")
    if isinstance(content, dict):
        content = content.get("text") or json.dumps(content)
    # Strip <think> tags from MiniMax reasoning
    import re as _re
    content = _re.sub(r"<think>.*?</think>", "", str(content), flags=_re.DOTALL).strip()
    return content, f"minimax/{model}"


def _call_openrouter(model, system, user, timeout=120):
[redacted secret-like line]
[redacted secret-like line]
    payload = {"model": model, "messages": [{"role": "system", "content": system}, {"role": "user", "content": user}]}
[redacted secret-like line]
    resp.raise_for_status()
    data = resp.json()
    choices = data.get("choices") or []
    if not choices:
        raise RuntimeError(f"OpenRouter no choices: {json.dumps(data)[:400]}")
    content = choices[0].get("message", {}).get("content", "")
    return str(content).strip(), f"openrouter/{model}"




def _call_ai(system, user, timeout=120):
    """Call AI with full fallback chain."""
    last_err = None
[redacted secret-like line]
        try:
            return _call_minimax(MINIMAX_MODEL, system, user, timeout)
        except Exception as e:
            last_err = e
            log.warning("MiniMax failed: %s", e)
[redacted secret-like line]
        for or_model in OPENROUTER_FREE_MODELS:
            try:
                return _call_openrouter(or_model, system, user, timeout)
            except Exception as e:
                last_err = e
                log.warning("OpenRouter %s failed: %s", or_model, e)
    raise RuntimeError(f"All AI providers failed: {last_err}")




def analyse_cope(text):
    """Analyse text for UK political/economic cope. Returns dict or None."""
    formatted = COPE_ANALYSIS_PROMPT.format(text=text[:5000])
    try:
        raw, model = _call_ai(UK_COPE_SYSTEM, formatted)
        raw = raw.strip()
        if raw.startswith("```"):
            raw = raw.split("\n", 1)[1]
            if raw.endswith("```"):
                raw = raw[:-3]
        result = json.loads(raw.strip())
        result["_model"] = model
        return result
    except json.JSONDecodeError:
        log.warning("JSON parse failed for cope analysis")
        return None
    except Exception as e:
        log.exception("Cope analysis failed: %s", e)
        return None


def score_oracle_month(month, data_dict):
    """AI-score a month of ONS data."""
    data_json = json.dumps(data_dict, indent=2)
    prompt = ORACLE_SCORING_PROMPT.format(month=month, data_json=data_json)
    try:
        raw, model = _call_ai(UK_COPE_SYSTEM, prompt)
        summary = gap = scapegoat = ""
        m = re.search(r"SUMMARY:\s*(.+?)(?=\n\s*GAP_ANALYSIS:|$)", raw, re.DOTALL)
        if m:
            summary = m.group(1).strip()
        m = re.search(r"GAP_ANALYSIS:\s*(.+?)(?=\n\s*SCAPEGOAT_CHECK:|$)", raw, re.DOTALL)
        if m:
            gap = m.group(1).strip()
        m = re.search(r"SCAPEGOAT_CHECK:\s*(.+)", raw, re.DOTALL)
        if m:
            scapegoat = m.group(1).strip()
        return summary, gap, scapegoat, model
    except Exception as e:
        log.exception("Oracle scoring failed: %s", e)
        return None, None, None, None


def generate_stats_commentary(month, data_dict):
    data_json = json.dumps(data_dict, indent=2)
    prompt = STATS_COMMENTARY_PROMPT.format(month=month, data_json=data_json)
    try:
        raw, model = _call_ai(UK_COPE_SYSTEM, prompt)
        return raw.strip(), model
    except Exception as e:
        log.exception("Stats commentary failed: %s", e)
        return None, None


def ask_oracle(question, data_context_dict):
    """Answer a user question about UK economic data.
    Uses MiniMax as primary (consistent with all other scoring), with full fallback chain.
    """
    data_context = json.dumps(data_context_dict, indent=2)
    prompt = ASK_ORACLE_PROMPT.format(data_context=data_context, question=question)

    # Use the standard fallback chain: MiniMax -> OpenRouter
    try:
        raw, model = _call_ai(ASK_ORACLE_SYSTEM, prompt, timeout=120)
        return raw.strip(), model
    except Exception as e:
        log.exception("Ask Oracle failed: %s", e)
        return None, None


def score_figure_cope(name, role, quote, context=""):
    prompt = FIGURE_COPE_PROMPT.format(name=name, role=role, quote=quote, context=context)
    try:
        raw, model = _call_ai(UK_COPE_SYSTEM, prompt)
        result = _parse_cope_response(raw)
        result["model"] = model
        return result
    except Exception as e:
        log.exception("Figure cope scoring failed: %s", e)
        return None



def strip_md(text):
    """Strip **bold** and *italic* markdown markers before regex parsing."""
    import re as _re
    text = _re.sub(r'\*\*([^*]+)\*\*', r'\1', text)
    text = _re.sub(r'\*([^*]+)\*', r'\1', text)
    # NOTE: Do NOT strip _ underscores -- they appear in field names like COPE_SCORE, COPE_TYPE
    return text


def _parse_cope_response(text):
    text = strip_md(text)  # Strip **bold** markdown before regex parsing
    result = {"cope_score": 50.0, "cope_type": "unknown", "cope_quote": "", "analysis": ""}
    m = re.search(r"COPE_SCORE:\s*(\d+)", text)
    if m:
        result["cope_score"] = min(100, max(0, float(m.group(1))))
    m = re.search(r"COPE_TYPE:\s*(.+?)(?:\n|$)", text)
    if m:
        result["cope_type"] = m.group(1).strip()
    m = re.search(r"COPE_QUOTE:\s*(.+?)(?:\n|$)", text)
    if m:
        result["cope_quote"] = m.group(1).strip()[:300]
    m = re.search(r"ANALYSIS:\s*(.+)", text, re.DOTALL)
    if m:
        result["analysis"] = m.group(1).strip()[:1000]
    return result


def extract_url_text(url):
    try:
        import trafilatura
        downloaded = trafilatura.fetch_url(url, no_ssl=False)
        if not downloaded:
            return None, None
        text = trafilatura.extract(downloaded, include_comments=False, include_tables=False, favor_recall=True) or ""
        title = None
        title_match = re.search(r'<title[^>]*>([^<]+)</title>', downloaded, re.IGNORECASE)
        if title_match:
            title = title_match.group(1).strip()
        if not title and text:
            title = text[:80].split("\n")[0]
        return text.strip(), title
    except Exception as e:
        log.warning("URL extraction failed for %s: %s", url, e)
        return None, None


def generate_figure_portrait(name, role, description=""):
    """Portrait generation is unavailable.

    Straico (retired 2026-07-06) was the only configured image provider and was
    removed on 2026-10-20. Returns None so callers use their existing
    no-portrait path. Wire a replacement provider in here if portraits return.
    """
    log.debug("portrait generation unavailable (no image provider): %s", name)
    return None


def download_image(url, save_path):
    try:
        resp = requests.get(url, timeout=30)
        resp.raise_for_status()
        with open(save_path, "wb") as f:
            f.write(resp.content)
        return True
    except Exception as e:
        log.warning("Image download failed: %s", e)
        return False


# --- ONS Bulletin Fetcher and Scorer ---

ONS_BULLETIN_TYPES = {
    "labour-market": {
        "name": "UK Labour Market",
        "base_url": "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/employmentandemployeetypes/bulletins/uklabourmarket",
        "latest_url": "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/employmentandemployeetypes/bulletins/uklabourmarket/latest",
        "frequency": "monthly",
    },
    "gdp": {
        "name": "GDP First Quarterly Estimate",
        "base_url": "https://www.ons.gov.uk/economy/grossdomesticproductgdp/bulletins/grossdomesticproductpreliminaryestimate",
        "latest_url": "https://www.ons.gov.uk/economy/grossdomesticproductgdp/bulletins/grossdomesticproductpreliminaryestimate/latest",
        "frequency": "quarterly",
    },
    "cpi": {
        "name": "Consumer Price Inflation",
        "base_url": "https://www.ons.gov.uk/economy/inflationandpriceindices/bulletins/consumerpriceinflation",
        "latest_url": "https://www.ons.gov.uk/economy/inflationandpriceindices/bulletins/consumerpriceinflation/latest",
        "frequency": "monthly",
    },
    "migration": {
        "name": "Long-term International Migration",
        "base_url": "https://www.ons.gov.uk/peoplepopulationandcommunity/populationandmigration/internationalmigration/bulletins/[redacted]",
        "latest_url": "https://www.ons.gov.uk/peoplepopulationandcommunity/populationandmigration/internationalmigration/bulletins/[redacted]/latest",
        "frequency": "quarterly",
    },
    "vacancies": {
        "name": "Vacancies and Jobs",
        "base_url": "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/employmentandemployeetypes/bulletins/jobsandvacanciesintheuk",
        "latest_url": "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/employmentandemployeetypes/bulletins/jobsandvacanciesintheuk/latest",
        "frequency": "monthly",
    },
}


def fetch_bulletin_text(url):
    """Fetch and extract full text from an ONS statistical bulletin."""
    try:
        import trafilatura
        downloaded = trafilatura.fetch_url(url, no_ssl=False)
        if not downloaded:
            log.warning("Could not download bulletin: %s", url)
            return None, None, None, url

        text = trafilatura.extract(
            downloaded,
            include_comments=False,
            include_tables=True,
            favor_recall=True,
            include_links=False,
        ) or ""

        # Extract title
        title = None
        title_match = re.search(r'<title[^>]*>([^<]+)</title>', downloaded, re.IGNORECASE)
        if title_match:
            title = title_match.group(1).strip()
            title = title.replace(" - Office for National Statistics", "").strip()

        # Extract date from the page
        date_str = None
        date_match = re.search(r'"datePublished"\s*:\s*"([^"]+)"', downloaded)
        if date_match:
            date_str = date_match.group(1)[:10]
        if not date_str:
            date_match = re.search(r'Release date:\s*(\d{1,2}\s+\w+\s+\d{4})', text)
            if date_match:
                date_str = date_match.group(1)

        # Resolve the canonical (dated) URL so each release is its own record.
        # ONS serves /latest directly with no HTTP redirect, so HEAD alone leaves
        # the alias in place -- and save_bulletin_analysis() upserts on
        # bulletin_url, so every release would overwrite the previous one's
        # score and provenance. The canonical link gives us e.g. .../october2026.
        final_url = url
        try:
            resp = requests.head(url, allow_redirects=True, timeout=10)
            final_url = resp.url
        except Exception:
            pass
        canon = re.search(
            r'<link[^>]+rel="canonical"[^>]+href="([^"]+)"', downloaded, re.I
        )
        if canon:
            href = canon.group(1).strip()
            if href.startswith("/"):
                href = "https://www.ons.gov.uk" + href
            if href.startswith("http"):
                final_url = href

        return text.strip(), title, date_str, final_url
    except Exception as e:
        log.exception("Bulletin fetch failed for %s: %s", url, e)
        return None, None, None, url


BULLETIN_SCORING_PROMPT = """You are the UK Oracle of Obsolescence analysing an official ONS statistical bulletin.

ONS bulletins are the official narrative wrapped around economic data. They contain framing choices, emphasis decisions, and language about "resilience" or "challenges" -- and sometimes they soft-pedal structural deterioration. Your job is to score the bulletin's framing through the structural reality lens.

BULLETIN TYPE: {bulletin_type}
BULLETIN TITLE: {title}

FULL BULLETIN TEXT:
{text}

Analyse this bulletin and return a JSON object with these fields:
{{
    "cope_score": integer 0-100 (how much is the ONS coping in their framing? 0=brutally honest, 100=pure copium),
    "analysis": "3-5 paragraphs of detailed analysis covering: what the bulletin emphasises vs what it downplays, language choices, gap between data and narrative framing, structural issues avoided",
    "key_data_points": ["list of 4-6 key data points extracted from the bulletin with brief context"],
    "what_they_said": "2-3 sentences summarising the ONS's own narrative/framing -- their headline takeaway",
    "what_data_shows": "2-3 sentences of what the data actually shows when read through the structural reality lens",
    "emphasis_vs_downplay": "What does the bulletin emphasise prominently vs what gets buried or omitted?",
    "language_choices": "Notable language choices -- words like 'resilient', 'robust', 'broadly stable' that paper over deterioration",
    "structural_issues_avoided": "What structural issues does this bulletin fail to mention or actively avoid?"
}}

SCORING GUIDE:
0-20: Admirably honest -- calls out structural problems directly
21-40: Mostly straight -- some soft framing but data is front and centre
41-60: Standard ONS -- technically accurate but framing choices obscure reality
61-80: Active cope -- language and emphasis systematically downplay bad news
81-100: Full copium -- bulletin reads like a press release from a government trying to avoid panic

Remember: The ONS is generally more honest than politicians, but they still make framing choices. Score the FRAMING, not the data quality.

Respond with ONLY valid JSON, no markdown formatting."""


def score_bulletin(bulletin_type, title, text):
    """Score an ONS bulletin through the structural reality lens via the standard AI chain."""
    if len(text) > 15000:
        text = text[:15000]

    prompt = BULLETIN_SCORING_PROMPT.format(
        bulletin_type=bulletin_type,
        title=title or "Unknown",
        text=text,
    )

    try:
        raw, model = _call_ai(UK_COPE_SYSTEM, prompt, timeout=240)
        raw = raw.strip()
        if raw.startswith("```"):
            raw = raw.split("\n", 1)[1]
            if raw.endswith("```"):
                raw = raw[:-3]
        result = json.loads(raw.strip())
        result["_model"] = model
        return result
    except json.JSONDecodeError as e:
        log.warning("JSON parse failed for bulletin scoring: %s", e)
        return None
    except Exception as e:
        log.exception("Bulletin scoring failed: %s", e)
        return None


def fetch_and_score_bulletin(bulletin_type):
    """Fetch the latest bulletin of the given type and score it."""
    if bulletin_type not in ONS_BULLETIN_TYPES:
        return None, f"Unknown bulletin type: {bulletin_type}"

    btype = ONS_BULLETIN_TYPES[bulletin_type]
    url = btype["latest_url"]

    result = fetch_bulletin_text(url)
    if result is None or result[0] is None:
        return None, f"Could not fetch bulletin from {url}"

    text, title, date_str, final_url = result
    if not text or len(text) < 200:
        return None, f"Bulletin text too short ({len(text) if text else 0} chars)"

    scoring = score_bulletin(btype["name"], title, text)
    if not scoring:
        return None, "AI scoring failed"

    return {
        "bulletin_type": bulletin_type,
        "bulletin_url": final_url,
        "bulletin_title": title or btype["name"],
        "bulletin_date": date_str,
        "raw_text": text,
        "cope_score": scoring.get("cope_score", 50),
        "ai_analysis": scoring.get("analysis", ""),
        "key_data_points": json.dumps(scoring.get("key_data_points", [])),
        "what_they_said": scoring.get("what_they_said", ""),
        "what_data_shows": scoring.get("what_data_shows", ""),
        "emphasis_vs_downplay": scoring.get("emphasis_vs_downplay", ""),
        "language_choices": scoring.get("language_choices", ""),
        "structural_issues_avoided": scoring.get("structural_issues_avoided", ""),
        "ai_model": scoring.get("_model", "unknown"),
    }, None
```
