---
type: "Source File"
title: "\"\"\""
description: "\"\"\" uk.copecheck.com -- UK Political & Economic Cope Tracker Flask app with Cope Table, Analyser, ONS Oracle, Interactive Stats, Ask the Oracle Q&A, Figure pages, and Scapegoat Tracker. \"\"\" import hashlib import hmac."
resource: "https://uk.copecheck.com"
tags: ["copecheck", "uk", "source-file", "py"]
timestamp: "2026-10-29T11:02:54Z"
site: "uk"
source_path: "copecheck-uk/app.py"
---

# """

Source path: `copecheck-uk/app.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-10-29T11:02:54Z`

```py
"""
uk.copecheck.com -- UK Political & Economic Cope Tracker
Flask app with Cope Table, Analyser, ONS Oracle, Interactive Stats,
Ask the Oracle Q&A, Figure pages, and Scapegoat Tracker.
"""
import hashlib
import hmac
import json
import logging
import os
import re
import tempfile
import threading
import time
from datetime import datetime, timezone
from functools import wraps
import markdown as md_lib
from pathlib import Path

from flask import (Flask, render_template, request, jsonify, g,
                   redirect, url_for, abort, Response)

import db_uk as db
import oracle_uk as oracle
import uk_labour_fetcher as labour_data
from seed_data import (FIGURES, COPE_CATEGORIES, SCAPEGOAT_NARRATIVES,
                       ONS_ORACLE_DATA, ONS_ORACLE_SUMMARIES,
                       STATS_DATA, STATS_COMMENTARY)

BASE = Path(__file__).parent
BASE_PATH = BASE
app = Flask(__name__, template_folder=str(BASE / "templates"),
            static_folder=str(BASE / "static"))


[redacted secret-like line]

PHOTOS_DIR = BASE / "static" / "photos"
PHOTOS_DIR.mkdir(parents=True, exist_ok=True)

_rate_store = {}
RATE_LIMIT_MAX = 5
RATE_LIMIT_WINDOW = 3600
_oracle_rate_store = {}
ORACLE_RATE_LIMIT_MAX = 10
ORACLE_RATE_LIMIT_WINDOW = 3600
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
    or ""
).strip()

[redacted secret-like line]
    ip = request.headers.get("X-Forwarded-For", request.remote_addr or "")
    return hashlib.sha256(ip.encode()).hexdigest()[:16]

[redacted secret-like line]
    now = time.time()
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
        wait = int(RATE_LIMIT_WINDOW - (now - oldest)) + 1
        return False, max(1, wait // 60)
    return True, 0

[redacted secret-like line]
    now = time.time()
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]

[redacted secret-like line]
    now = time.time()
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
        wait = int(ORACLE_RATE_LIMIT_WINDOW - (now - oldest)) + 1
        return False, max(1, wait // 60)
    return True, 0

[redacted secret-like line]
    now = time.time()
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]

[redacted secret-like line]
[redacted secret-like line]
    if auth.lower().startswith("bearer "):
        return auth.split(" ", 1)[1].strip()
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
    if request.is_json:
        body = request.get_json(silent=True) or {}
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]

def _admin_authorised():
[redacted secret-like line]
[redacted secret-like line]

def _admin_required(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
[redacted secret-like line]
[redacted secret-like line]
        if not _admin_authorised():
            return jsonify({"error": "admin_auth_required"}), 401
        return fn(*args, **kwargs)
    return wrapper

def _cope_color(score):
    if score is None: return "cope-unknown"
    s = float(score)
    if s <= 20: return "cope-lucid"
    elif s <= 40: return "cope-partial"
    elif s <= 60: return "cope-moderate"
    elif s <= 80: return "cope-heavy"
    else: return "cope-terminal"

def _cope_label(score):
    if score is None: return "UNSCORED"
    s = float(score)
    if s <= 20: return "LUCID"
    elif s <= 40: return "PARTIAL"
    elif s <= 60: return "MODERATE"
    elif s <= 80: return "HEAVY COPE"
    else: return "TERMINAL COPIUM"

app.jinja_env.filters["copecolor"] = _cope_color
app.jinja_env.filters["copelabel"] = _cope_label
def _render_md(text):
    if not text: return ""
    return md_lib.markdown(text)
app.jinja_env.filters["render_md"] = _render_md

def _render_verdict(text):
    """Render markdown text to HTML, stripping raw artifacts."""
    if not text:
        return ""
    return md_lib.markdown(text)
app.jinja_env.filters["render_verdict"] = _render_verdict

def _strip_md(text):
    """Strip all markdown formatting to plain text."""
    if not text:
        return ""
    import re as _re
    text = _re.sub(r"^#{1,6}\s+", "", text, flags=_re.MULTILINE)
    text = _re.sub(r"\*\*(.+?)\*\*", r"\1", text)
    text = _re.sub(r"\*(.+?)\*", r"\1", text)
    text = _re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text)
    text = _re.sub(r"`([^`]+)`", r"\1", text)
    return text
app.jinja_env.filters["strip_md"] = _strip_md

def _clean_share_fragment(value, limit=140):
    text = _strip_md(str(value or ""))
    text = text.strip('"\'"\u201c\u201d\u2018\u2019')
    text = re.sub(r"\s+", " ", text).strip()
    if len(text) > limit:
        text = text[:limit - 1].rsplit(" ", 1)[0].rstrip(".,;:") + "."
    return text


UK_SHARE_OVERRIDES = {
    "farage": "Nigel Farage is coping by making immigration carry the whole weight of Britain's economic failure, as if stricter borders would stop AI, weak productivity, housing costs, weak public capacity and a breaking labour market from liquidating the old settlement. It is effective politics, but it is not an economic theory; it is a scapegoat with a microphone.",
    "starmer": "Keir Starmer is coping by narrating national renewal while the structural engine underneath the UK economy keeps weakening. The pitch is stability, missions and responsible management; the reality is a labour market being squeezed by automation, low investment, housing costs, sickness and state capacity limits.",
    "sunak": "Rishi Sunak is coping by treating AI disruption as a skills-and-opportunity story after spending years selling Britain as a frontier AI state. He sees enough of the shock to sound serious, then folds it back into the familiar promise that adaptation, training and entrepreneurial energy will absorb the damage.",
    "khan": "Sadiq Khan is coping by turning London's exposure to AI and high-cost stagnation into a growth-plan story. London can promise jobs, skills and investment, but it is also the city where white-collar automation, rent extraction and public-service strain collide first.",
    "reeves": "Rachel Reeves is coping by making fiscal discipline and global headwinds do too much explanatory work. The Treasury story is prudence and stability; the structural story is weaker growth, squeezed households, fragile jobs and an AI shock that does not fit neatly inside old Budget language.",
    "badenoch": "Kemi Badenoch is coping by turning Britain's economic malaise into a culture-war and competence story. That lands politically, but it dodges the harder question: what happens when automation, weak productivity, housing and public-service decay are doing more damage than the chosen villains.",
    "jenrick": "Robert Jenrick is coping by making state waste, welfare and Labour tax choices carry more explanatory weight than they can bear. It is a clean opposition attack, but the deeper pressures are automation, low productivity, expensive housing and a labour market losing its old absorption capacity.",
    "tice": "Richard Tice is coping by framing decline as a story of regulation, net zero and political betrayal. Those are useful targets, but they do not explain away the larger discontinuity: Britain is trying to preserve old jobs and old growth assumptions while AI and capital keep changing the terms of work.",
}


def _uk_share_paragraph(fig):
    fig_id = str(fig.get("id") or "")
    if fig_id in UK_SHARE_OVERRIDES:
        return UK_SHARE_OVERRIDES[fig_id]

    name = fig.get("name") or "This figure"
    scapegoat = fig.get("scapegoat_of_choice") or "the convenient villain"
    category = (fig.get("category") or "").lower()
    mode = _clean_share_fragment(fig.get("last_cope_type"), 90)
    quote = _clean_share_fragment(fig.get("last_quote"), 150)
    score = float(fig.get("cope_score") or 0)

    if "scapegoater" in category:
        base = (
            f"{name} is coping by making {scapegoat} do the work of an economic theory. "
            "The move is simple: give voters a visible culprit while the harder forces, automation, weak productivity, housing, health and state capacity, stay safely offstage."
        )
    elif "gaslighter" in category:
        base = (
            f"{name} is coping by describing managed recovery while the numbers point to a more brittle economy. "
            "The public story asks for patience; the structural story is that wages, services, work and AI exposure are not waiting politely."
        )
    elif "deflector" in category:
        base = (
            f"{name} is coping by shifting attention toward {scapegoat} and away from the machinery underneath. "
            "That can be clever politics, but it leaves the real economic pressures, automation, low investment, housing costs and institutional exhaustion, mostly untouched."
        )
    elif "structural_critic" in category:
        base = (
            f"{name} is closer to the structure than most, but still gets scored when the argument collapses into a familiar blame story. "
            "The useful question is not only who is at fault; it is whether the old labour-market settlement can survive AI and capital doing more of the work."
        )
    else:
        base = (
            f"{name} is coping because the explanation is smaller than the problem. "
            "Britain's economic stress is not one villain, one policy lever or one slogan; it is automation, low productivity, housing, health and public capacity grinding against each other."
        )

    if score >= 75:
        base += " That is why the score is high."
    elif score <= 25:
        base += " The lower score means the Oracle sees less denial here, but the figure still belongs on the watchlist."
    if mode and mode.lower() not in {"none", "n/a", "not_attributed"}:
        base += f" Latest mode: {mode}."
    if quote and quote.lower() != "n/a":
        base += f" Latest tell: \"{quote}\""
    return base


def _attach_uk_share_copy(fig):
    url = f"https://uk.copecheck.com/figure/{fig.get('id')}"
    paragraph = _uk_share_paragraph(fig)
    score = int(round(float(fig.get("cope_score") or 0)))
    fig["share_paragraph"] = paragraph
    fig["share_text"] = f"{paragraph}\n\n{fig.get('name') or 'This figure'} scores {score}/100 on UK CopeCheck: {url}"
    return fig

def _oracle_verdict(text):
    if not text:
        return ""
    import re as _re
    text = text.strip()
    # Strip markdown headings
    text = _re.sub(r"^#{1,6}\s+", "", text, flags=_re.MULTILINE)
    # Strip markdown bold/italic markers
    text = _re.sub(r"\*\*(.+?)\*\*", r"\1", text)
    text = _re.sub(r"\*(.+?)\*", r"\1", text)
    # Strip markdown links [text](url) -> text
    text = _re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text)
    para = text.split("\n\n")[0].strip()
    if len(para) > 300:
        para = para[:297].rsplit(" ", 1)[0] + "..."
    return para
app.jinja_env.filters["oracle_verdict"] = _oracle_verdict
app.jinja_env.globals["now"] = datetime.utcnow
app.jinja_env.globals["categories"] = COPE_CATEGORIES

def seed_database():
    for fig in FIGURES:
        db.upsert_figure(fig["id"], fig["name"], fig["role"], fig.get("party"), fig["type"], fig["category"], fig["cope_score"], fig["latest_incident"], fig["scapegoat_of_choice"], fig["cope_streak_days"], photo_url=fig.get("photo_url", ""), watch_for=",".join(fig.get("watch_for", [])), why_monitor=fig.get("why_monitor", ""))
        if "active" in fig:
            db.set_figure_active(fig["id"], fig.get("active", True), fig.get("archived_reason", ""))
    for narr in SCAPEGOAT_NARRATIVES:
        db.upsert_narrative(narr["id"], narr["narrative"], narr["scapegoat"], narr["reality"], narr["data_source"], narr["times_invoked"], narr["trend"])
    for data in ONS_ORACLE_DATA:
        month = data["month"]
        summaries = ONS_ORACLE_SUMMARIES.get(month, {})
        db.save_oracle_month(month=month, data_json=data, ai_summary=summaries.get("summary"), ai_gap_analysis=summaries.get("gap_analysis"), ai_scapegoat_check=summaries.get("scapegoat_check"), ai_model="seed")
    for data in STATS_DATA:
        month = data["month"]
        commentary = STATS_COMMENTARY.get(month)
        db.save_stats_month(month=month, data_json=data, ai_commentary=commentary, ai_model="seed")

db.init()
with app.app_context():
    seed_database()
    try:
        import ons_data
        months = ons_data.fetch_all_latest(num_months=60)
        for month_data in months:
            month = month_data["month"]
            existing = db.get_stats_by_month(month)
            if existing:
                current_data = existing.get("data") or {}
                merged_data = dict(current_data)
                for key, value in month_data.items():
                    if value is not None:
                        merged_data[key] = value
                if merged_data != current_data:
                    db.save_stats_month(
                        month=month,
                        data_json=merged_data,
                        ai_commentary=existing.get("ai_commentary"),
                        ai_model=existing.get("ai_model") or "ons-api",
                    )
                    logging.info("Merged real ONS data for %s", month)
            else:
                db.save_stats_month(month=month, data_json=month_data, ai_model="ons-api")
                logging.info("Loaded real ONS data for %s", month)
    except Exception as e:
        logging.warning("Could not load ONS data on startup: %s", e)

# ── CDN & Cache Headers ──────────────────────────────────────
@app.after_request
def add_cache_headers(response):
    """Set cache headers for Cloudflare CDN."""
    path = request.path
    if path.startswith('/static/'):
        # Static assets: cache aggressively at CDN and browser
        response.headers['Cache-Control'] = 'public, max-age=604800, stale-while-revalidate=86400'
    elif path.startswith('/api/'):
        # API responses: never cache
        response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0'
    elif path.endswith('.xml'):
        # Sitemaps/feeds: cache 1 hour
        response.headers['Cache-Control'] = 'public, max-age=3600'
    else:
        # HTML pages: short cache, but allow CDN to serve stale during spikes
        response.headers['Cache-Control'] = 'public, max-age=300, stale-while-revalidate=3600, stale-if-error=86400'
    # Vary by encoding so CDN caches gzip and plain separately
    response.headers.setdefault('Vary', 'Accept-Encoding')
    response.headers.setdefault('X-Content-Type-Options', 'nosniff')
    response.headers.setdefault('X-Frame-Options', 'DENY')
    response.headers.setdefault('Referrer-Policy', 'strict-origin-when-cross-origin')
    response.headers.setdefault('Permissions-Policy', 'camera=(), microphone=(), geolocation=(), interest-cohort=()')
    return response

@app.route("/")
def index():
    figures = db.get_leaderboard()
    for fig in figures:
        _attach_uk_share_copy(fig)
        fig["entries"] = db.figure_entries(fig["id"], limit=3)
    return render_template("index.html", figures=figures, categories=COPE_CATEGORIES, now=datetime.utcnow())

@app.route("/figure/<figure_id>")
def figure_page(figure_id):
    fig = db.get_figure(figure_id)
    if not fig: abort(404)
    _attach_uk_share_copy(fig)
    entries = db.figure_entries(figure_id, limit=50)
    score_history = db.figure_score_history(figure_id)
    return render_template("figure.html", fig=fig, entries=entries, score_history=score_history, categories=COPE_CATEGORIES)

@app.route("/analyser")
def analyser():
    recent = db.recent_analyses(limit=10)
    return render_template("analyser.html", recent=recent)

@app.route("/api/analyse", methods=["POST"])
def api_analyse():
[redacted secret-like line]
[redacted secret-like line]
    if not allowed:
        return jsonify({"error": f"Rate limited. Try again in {wait_mins} minutes."}), 429
    data = request.get_json()
    text = (data.get("text") or "").strip()
    if not text: return jsonify({"error": "No text provided"}), 400
    if len(text) > 10000: return jsonify({"error": "Text too long (max 10000 chars)"}), 400
    input_url = None
    extracted_title = None
    if text.startswith(("http://", "https://")) and " " not in text[:200]:
        input_url = text
        article_text, title = oracle.extract_url_text(input_url)
        if not article_text or len(article_text) < 100:
            return jsonify({"error": "Could not extract enough text from that URL."}), 400
        extracted_title = title
        text = article_text
        if len(text) > 8000: text = text[:8000]
    result = oracle.analyse_cope(text)
    if result:
[redacted secret-like line]
        model = result.pop("_model", "unknown")
[redacted secret-like line]
        result["slug"] = slug
        if extracted_title: result["extracted_title"] = extracted_title
        return jsonify(result)
    else:
        return jsonify({"error": "All AI models failed. Try again shortly."}), 503

@app.route("/analysis/<slug>")
def analysis_detail(slug):
    row = db.get_analysis_by_slug(slug)
    if not row: abort(404)
    return render_template("analysis.html", a=row)

@app.route("/oracle")
def oracle_page():
    return redirect(url_for("data_page"))

@app.route("/oracle/<month>")
def oracle_month(month):
    entry = db.get_oracle_by_month(month)
    if not entry: abort(404)
    return render_template("oracle_month.html", entry=entry)

@app.route("/api/oracle/rescore/<month>", methods=["POST"])
def api_oracle_rescore(month):
    entry = db.get_oracle_by_month(month)
    if not entry: return jsonify({"error": "Month not found"}), 404
    summary, gap, scapegoat, model = oracle.score_oracle_month(month, entry["data"])
    if summary:
        db.save_oracle_month(month=month, data_json=entry["data"], ai_summary=summary, ai_gap_analysis=gap, ai_scapegoat_check=scapegoat, ai_model=model)
        return jsonify({"ok": True, "model": model})
    return jsonify({"error": "AI scoring failed"}), 503

@app.route("/stats")
def stats_page():
    return redirect(url_for("data_page"))

@app.route("/data")
def data_page():
    # Stats data
    stats_archive = db.get_stats_archive(limit=60)
    stats_latest = stats_archive[0] if stats_archive else None
    figures_with_entries = db.get_figures_with_recent_entries(limit=5)
    # Oracle data
    oracle_archive = db.get_oracle_archive(limit=6)
    oracle_latest = oracle_archive[0] if oracle_archive else None
    # Bulletins
    bulletins = db.get_bulletin_analyses(limit=20)
    import json as _json
    for b in bulletins:
        try:
            b["key_data_points_list"] = _json.loads(b.get("key_data_points") or "[]")
        except Exception:
            b["key_data_points_list"] = []
    # Find latest month with net_migration data
    migration_latest = None
    for s in stats_archive:
        if s.get("data") and s["data"].get("net_migration") is not None:
            migration_latest = {"month": s["month"], "value": s["data"]["net_migration"]}
            break
    return render_template("data.html",
                           stats_latest=stats_latest, stats_archive=stats_archive,
                           oracle_latest=oracle_latest, oracle_archive=oracle_archive,
                           bulletins=bulletins, figures_with_entries=figures_with_entries,
                           migration_latest=migration_latest)

@app.route("/api/stats/refresh", methods=["POST"])
@_admin_required
def api_stats_refresh():
    try:
        import ons_data
        months = ons_data.fetch_all_latest(num_months=60)
        count = 0
        for month_data in months:
            db.save_stats_month(month=month_data["month"], data_json=month_data, ai_model="ons-api")
            count += 1
        return jsonify({"ok": True, "months_updated": count})
    except Exception as e:
        return jsonify({"error": str(e)}), 503

@app.route("/ask-oracle")
def ask_oracle_page():
    recent = db.get_recent_questions(limit=10)
    return render_template("ask_oracle.html", recent=recent)

@app.route("/api/ask-oracle", methods=["POST"])
def api_ask_oracle():
[redacted secret-like line]
[redacted secret-like line]
    if not allowed:
        return jsonify({"error": f"Rate limited. Try again in {wait_mins} minutes."}), 429
    data = request.get_json()
    question = (data.get("question") or "").strip()
    if not question: return jsonify({"error": "No question provided"}), 400
    if len(question) > 2000: return jsonify({"error": "Question too long (max 2000 chars)"}), 400
    archive = db.get_stats_archive(limit=6)
    if not archive:
        return jsonify({"error": "No economic data available yet."}), 503
    data_context = {}
    for entry in reversed(archive[:6]):
        data_context[entry["month"]] = entry["data"]
    answer, model = oracle.ask_oracle(question, data_context)
    if answer:
[redacted secret-like line]
[redacted secret-like line]
        return jsonify({"answer": answer, "model": model, "question_id": qid})
    else:
        return jsonify({"error": "The Oracle is unavailable. Try again shortly."}), 503

@app.route("/scapegoats")
def scapegoats():
    narratives = db.get_narratives()
    return render_template("scapegoats.html", narratives=narratives)

@app.route("/feed")
def feed():
    page = request.args.get("page", 1, type=int)
    per_page = 20
    all_entries = db.get_all_recent_entries(limit=200)
    total_pages = max(1, (len(all_entries) + per_page - 1) // per_page)
    page = max(1, min(page, total_pages))
    entries = all_entries[(page-1)*per_page : page*per_page]
    return render_template("feed.html", entries=entries, page=page, total_pages=total_pages)

@app.route("/about")
def about():
    return render_template("about.html")

@app.route("/ai-disclosure")
def ai_disclosure():
    return render_template("ai_disclosure.html")

@app.route("/health")
def health():
    c = db.counts()
    return jsonify({"status": "ok", "service": "copecheck-uk", "counts": c, "timestamp": datetime.utcnow().isoformat()})

@app.route("/api/generate-portrait/<figure_id>", methods=["POST"])
@_admin_required
def api_generate_portrait(figure_id):
    fig = db.get_figure(figure_id)
    if not fig: return jsonify({"error": "Figure not found"}), 404
    description = f"UK {'politician' if fig['type'] == 'politician' else 'business figure'}"
    if fig.get("party"): description += f", {fig['party']}"
    image_url = oracle.generate_figure_portrait(fig["name"], fig["role"], description)
    if not image_url: return jsonify({"error": "Image generation failed"}), 503
    filename = f"{figure_id}.png"
    save_path = str(PHOTOS_DIR / filename)
    if oracle.download_image(image_url, save_path):
        local_url = f"/static/photos/{filename}"
        db.update_figure_photo(figure_id, local_url)
        return jsonify({"ok": True, "photo_url": local_url})
    db.update_figure_photo(figure_id, image_url)
    return jsonify({"ok": True, "photo_url": image_url})



# --- Bulletin analysis routes ---

@app.route("/api/bulletin/fetch", methods=["POST"])
@_admin_required
def api_bulletin_fetch():
    """Fetch and score the latest ONS bulletin of a given type."""
    data = request.get_json() or {}
    bulletin_type = data.get("type", "labour-market")

    if bulletin_type not in oracle.ONS_BULLETIN_TYPES:
        return jsonify({"error": f"Unknown bulletin type: {bulletin_type}",
                        "valid_types": list(oracle.ONS_BULLETIN_TYPES.keys())}), 400

    result, err = oracle.fetch_and_score_bulletin(bulletin_type)
    if not result:
        return jsonify({"error": err}), 503

    bid = db.save_bulletin_analysis(**result)
    return jsonify({
        "ok": True,
        "id": bid,
        "title": result["bulletin_title"],
        "cope_score": result["cope_score"],
        "url": result["bulletin_url"],
    })


@app.route("/api/bulletin/fetch-all", methods=["POST"])
@_admin_required
def api_bulletin_fetch_all():
    """Fetch and score all bulletin types."""
    results = []
    for btype in oracle.ONS_BULLETIN_TYPES:
        try:
            result, err = oracle.fetch_and_score_bulletin(btype)
            if result:
                bid = db.save_bulletin_analysis(**result)
                results.append({"type": btype, "id": bid, "score": result["cope_score"],
                                "title": result["bulletin_title"]})
            else:
                results.append({"type": btype, "error": err})
        except Exception as e:
            results.append({"type": btype, "error": str(e)})
    return jsonify({"ok": True, "results": results})


@app.route("/bulletin/<int:bid>")
def bulletin_detail(bid):
    """View a single bulletin analysis."""
    b = db.get_bulletin_by_id(bid)
    if not b:
        abort(404)
    import json as _json
    try:
        b["key_data_points_list"] = _json.loads(b.get("key_data_points") or "[]")
    except Exception:
        b["key_data_points_list"] = []
    return render_template("bulletin.html", b=b)




# --- Pipeline Admin Review ---

@app.route("/admin/review")
@_admin_required
def admin_review():
    """Admin page showing pipeline results that need review."""
    pending = db.get_needs_review(limit=50)
    return render_template("admin_review.html", pending=pending)


@app.route("/api/admin/review", methods=["GET"])
@_admin_required
def api_admin_review_list():
    """API: list pipeline results needing review."""
    pending = db.get_needs_review(limit=50)
    return jsonify({"results": pending, "count": len(pending)})


@app.route("/api/admin/review/<int:result_id>", methods=["GET"])
@_admin_required
def api_admin_review_detail(result_id):
    """API: get a single pipeline result for review."""
    result = db.get_pipeline_result(result_id)
    if not result:
        return jsonify({"error": "Not found"}), 404
    return jsonify(result)


@app.route("/api/admin/review/<int:result_id>", methods=["POST"])
@_admin_required
def api_admin_review_action(result_id):
    """API: approve or reject a pipeline result."""
    data = request.get_json() or {}
    action = data.get("action", "")  # "approve" or "reject"
    if action not in ("approve", "reject"):
        return jsonify({"error": "action must be 'approve' or 'reject'"}), 400

    result = db.get_pipeline_result(result_id)
    if not result:
        return jsonify({"error": "Not found"}), 404

    if action == "approve":
        db.update_review_status(result_id, "approved")
    else:
        db.update_review_status(result_id, "rejected")

    return jsonify({"ok": True, "action": action, "result_id": result_id})


@app.route("/api/pipeline/score", methods=["POST"])
@_admin_required
def api_pipeline_score():
    """API: manually trigger pipeline scoring for a URL + figure."""
    data = request.get_json() or {}
    url = (data.get("url") or "").strip()
    figure_id = (data.get("figure_id") or "").strip()

    if not url or not figure_id:
        return jsonify({"error": "url and figure_id required"}), 400

    fig = db.get_figure(figure_id)
    if not fig:
        return jsonify({"error": f"Figure {figure_id} not found"}), 404

    import scoring_pipeline

    person = {
        "id": figure_id,
        "name": fig["name"],
        "role": fig.get("role", ""),
        "party": fig.get("party", ""),
    }

    try:
        result = scoring_pipeline.score_article(
            url=url,
            person=person,
            source_name=data.get("source_name", ""),
        )
        scoring_pipeline.save_raw_log(result, figure_id)

        if result.get("published") and result.get("score"):
            scoring_pipeline.save_pipeline_result(result, figure_id, db)

        return jsonify({
            "ok": True,
            "published": result.get("published", False),
            "score": result.get("score"),
            "model": result.get("model"),
            "stage": result.get("stage"),
            "reject_reason": result.get("reject_reason"),
        })
    except Exception as e:
        return jsonify({"error": str(e)}), 503



@app.route("/labour-market")
def labour_market_page():
    ons_vacancies = None
    stats_archive = db.get_stats_archive(limit=3)
    for s in stats_archive:
        if s.get("data") and s["data"].get("vacancies") is not None:
            ons_vacancies = {"value": s["data"]["vacancies"], "month": s["month"]}
            break
    rec_latest = labour_data.get_latest_rec_report()
    adzuna_latest = labour_data.get_latest_adzuna()
    ai_tracker = labour_data.get_ai_redundancy_tracker()
    vacs02_rows = labour_data.get_latest_vacs02()
    return render_template("labour_market.html",
                           ons_vacancies=ons_vacancies,
                           rec_latest=rec_latest,
                           adzuna_latest=adzuna_latest,
                           ai_tracker=ai_tracker,
                           vacs02_rows=vacs02_rows)

@app.route("/api/labour-market/refresh", methods=["POST"])
@_admin_required
def api_labour_market_refresh():
    try:
        labour_data.run_all(seed_ai=True, fetch_vacs02_data=True,
                            fetch_rec=True, fetch_adzuna_data=True)
        return jsonify({"ok": True})
    except Exception as e:
        return jsonify({"error": str(e)}), 503

@app.errorhandler(404)
def not_found(e):
    return render_template("404.html"), 404

@app.errorhandler(500)
def server_error(e):
    return render_template("500.html"), 500



# ── ASYNC_YOUTUBE_ROUTES_PATCH ───────────────────────────────────────────────
# Async YouTube scoring pipeline — queues immediately, cc-node-01 worker scores

[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
    or ""
).strip()


def _worker_auth():
[redacted secret-like line]
    cands = [
[redacted secret-like line]
[redacted secret-like line]
    ]
    if request.is_json:
[redacted secret-like line]
    candidate = next((c for c in cands if c), "")
[redacted secret-like line]
[redacted secret-like line]


# ── YT_QUEUE_BACKSTOP_PATCH: logging under gunicorn (added 2026-10-04) ──────
# app.py is imported by wsgi:app, so the logging.basicConfig() in the
# __main__ block at the bottom of this file never executes in production.
# Without it the root logger stays at WARNING with no handler of its own, so
# every logging.info() below - including the watchdog's account of what it
# recovered and why - was silently dropped. Configure it at import time,
# guarded so it cannot duplicate handlers if something else got there first.
_yt_root_logger = logging.getLogger()
if not _yt_root_logger.handlers:
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s %(levelname)s [%(name)s] %(message)s",
    )
if _yt_root_logger.level == logging.NOTSET or _yt_root_logger.level > logging.INFO:
    _yt_root_logger.setLevel(logging.INFO)


def _start_youtube_recovery(video_id, worker_data):
    """Return a watchdog-claimed job to the worker under the shared retry cap.

    The old background thread routed to a retired Mac proxy and failed outside
    the retry budget. SQLite owns this transition across all Gunicorn workers.
    """
    error = str(worker_data.get("error") or "Worker stopped reporting")
    resolution = db.resolve_youtube_worker_failure(
        video_id, error, "resource", True, "watchdog recovery",
    )
    if resolution["status"] == "noop":
        return False
    outcome = "exhausted" if resolution["exhausted"] else "retrying"
    db.log_youtube_score_attempt(
        video_id, worker_data.get("title"), resolution["attempts"],
        outcome + ":resource", error,
    )
    logging.warning("YouTube watchdog resolved %s: %s (%d/%d attempts)",
                    video_id, resolution["status"], resolution["attempts"],
                    db.YOUTUBE_MAX_SCORE_ATTEMPTS)
    return True


# The cc-node-01 worker drains the queue SERIALLY and polls every 60s, so a job
# sitting in 'queued' while another is 'processing' is waiting its turn, not
# abandoned. The old 2-minute grace treated ordinary queueing as failure: when
# one video ran long, the watchdog "recovered" the videos behind it and ended up
# marking an innocent one failed. Grace now covers a full worker cycle, and
# queued recovery is additionally suppressed while the worker is visibly busy
# (see _recover_stale_youtube_jobs).
YOUTUBE_QUEUE_GRACE_SECONDS = 10 * 60
# Worker requests have 180s and 120s read timeouts, plus
# transcript fetch and post overhead. 25 minutes leaves headroom without letting
# a genuinely dead job sit forever.
YOUTUBE_PROCESSING_TIMEOUT_SECONDS = 25 * 60
# Last line of defence for ownerless jobs. Recovery normally requeues or fails
# under the shared attempt cap; this catches rows that evade those transitions.
YOUTUBE_HARD_CEILING_SECONDS = 2 * 60 * 60
# Worker lease TTL. The worker renews its claim every 60s while holding a job,
# so three missed beats is strong evidence the holder is gone. This is what the
# 2026-10-03 failure actually needed: the worker process stayed alive but
# stopped making progress, so nothing crashed, nothing restarted, the row sat
# 'processing', and - worse - it counted as "busy" and suppressed recovery of
# everything queued behind it. With a lease, a dead holder is detected in ~3
# minutes instead of 25 and stops blocking the queue immediately.
YOUTUBE_LEASE_TTL_SECONDS = 3 * 60


def _recover_stale_youtube_jobs():
    """Recover jobs abandoned before or after an external worker claim."""
    try:
        # A 'processing' row with no processing_started_at is unreachable by
        # every other path here (they all filter on IS NOT NULL), by the worker
        # (it only polls 'queued'), and by resubmission (queue_youtube_video
        # refuses rows already 'processing'). Give it a clock so the timeout and
        # ceiling logic below can take ownership of it.
        healed = db.heal_youtube_null_processing_timestamps()
        if healed:
            logging.warning(
                "Backfilled processing_started_at for %d clockless YouTube job(s)",
                healed,
            )
        # Serial worker: while it is demonstrably processing something, every
        # other queued job is waiting by design. Recovering those duplicates
        # work and can mark a perfectly healthy video failed.
        busy = db.count_active_processing_youtube_videos(
            YOUTUBE_PROCESSING_TIMEOUT_SECONDS,
            lease_ttl_seconds=YOUTUBE_LEASE_TTL_SECONDS,
        )
        queued_jobs = db.get_stale_queued_youtube_videos(
            YOUTUBE_QUEUE_GRACE_SECONDS
        )
        if busy and queued_jobs:
            logging.info(
                "Worker is processing %d video(s); leaving %d queued job(s) to "
                "wait their turn instead of recovering them",
                busy, len(queued_jobs),
            )
            queued_jobs = []
        for job in queued_jobs:
            video_id = job["video_id"]
            if not db.claim_stale_queued_youtube_recovery(
                video_id, YOUTUBE_QUEUE_GRACE_SECONDS
            ):
                continue
            if _start_youtube_recovery(
                video_id,
                {
                    "title": "",
                    "channel": "",
                    "error": "Worker did not claim queued job",
                },
            ):
                logging.warning(
                    "YouTube job was unclaimed for %ds; resolved through bounded worker recovery: %s",
                    YOUTUBE_QUEUE_GRACE_SECONDS,
                    video_id,
                )
            else:
                # Claim was stamped but no thread started (already in flight in
                # this process). Hand the claim back rather than spending a
                # whole timeout window on a recovery that is not happening.
                db.release_youtube_recovery_claim(video_id)

        # ── Expired-lease pass ───────────────────────────────────────────────
        # Runs before the processing-timeout pass below because it is strictly
        # better evidence: a missed heartbeat says the holder is gone now,
        # whereas the timeout only says the job is old. Jobs from a worker that
        # never sends a heartbeat have a NULL lease and are skipped here, so
        # they still fall through to the timeout path unchanged.
        for job in db.get_expired_lease_youtube_videos(YOUTUBE_LEASE_TTL_SECONDS):
            video_id = job["video_id"]
            if not db.claim_expired_lease_youtube_recovery(
                video_id, YOUTUBE_LEASE_TTL_SECONDS
            ):
                continue
            if _start_youtube_recovery(
                video_id,
                {
                    "title": job.get("title") or "",
                    "channel": job.get("channel") or "",
                    "error": "Worker lease expired (heartbeat stopped)",
                },
            ):
                logging.warning(
                    "YouTube worker lease expired (no heartbeat since %s, TTL "
                    "%ds); resolved through bounded worker recovery: %s",
                    job.get("lease_renewed_at"), YOUTUBE_LEASE_TTL_SECONDS,
                    video_id,
                )
            else:
                db.release_youtube_recovery_claim(video_id)

        stale_jobs = db.get_stale_processing_youtube_videos(
            YOUTUBE_PROCESSING_TIMEOUT_SECONDS
        )
        for job in stale_jobs:
            video_id = job["video_id"]
            if not db.claim_stale_youtube_recovery(
                video_id, YOUTUBE_PROCESSING_TIMEOUT_SECONDS
            ):
                continue
            started = _start_youtube_recovery(
                video_id,
                {
                    "title": job.get("title") or "",
                    "channel": job.get("channel") or "",
                    "error": "Worker processing timeout",
                },
            )
            if started:
                logging.warning(
                    "YouTube job exceeded %ds; resolved through bounded worker recovery: %s",
                    YOUTUBE_PROCESSING_TIMEOUT_SECONDS,
                    video_id,
                )
            else:
                db.release_youtube_recovery_claim(video_id)

        # ── Hard-ceiling backstop ────────────────────────────────────────────
        # Everything above *starts* work. This is the only step that guarantees
        # an end. Any job still non-terminal past the ceiling is declared
        # failed, so it stops being an invisible permanent resident of the
        # queue and becomes something the estate check reports and the user can
        # resubmit. Age is computed with COALESCE over every timestamp column,
        # so a row cannot dodge the backstop by having a missing clock.
        for job in db.get_ownerless_youtube_jobs(YOUTUBE_HARD_CEILING_SECONDS):
            video_id = job["video_id"]
            reason = (
                "Abandoned with no owner: still '%s' %d+ minutes after work "
                "began (worker never reported and server recovery did not "
                "complete). Marked failed by the watchdog backstop so it is "
                "visible and can be resubmitted."
                % (job.get("status") or "unknown",
                   YOUTUBE_HARD_CEILING_SECONDS // 60)
            )
            if db.abandon_youtube_job(
                video_id, reason, YOUTUBE_HARD_CEILING_SECONDS
            ):
                logging.error(
                    "YouTube job exceeded hard ceiling of %ds with no terminal "
                    "state; marked failed: %s (status was %s, since %s)",
                    YOUTUBE_HARD_CEILING_SECONDS, video_id,
                    job.get("status"), job.get("since"),
                )
    except Exception:
        logging.exception("Stale YouTube job watchdog failed")


def _youtube_watchdog_loop():
    while True:
        time.sleep(60)
        _recover_stale_youtube_jobs()


threading.Thread(
    target=_youtube_watchdog_loop,
    name="youtube-stale-watchdog",
    daemon=True,
).start()


@app.route("/youtube")
def youtube_page():
    _recover_stale_youtube_jobs()
    videos = db.get_all_youtube_videos(limit=100)
    return render_template("youtube.html", videos=videos)


@app.route("/youtube/<video_id>")
def youtube_detail(video_id):
    video = db.get_youtube_video(video_id)
    if not video:
        return "Video not found", 404
    return render_template("youtube_detail.html", video=video)


@app.route("/youtube/<video_id>/status")
def youtube_status(video_id):
    """Polling endpoint — returns current scoring status as JSON."""
    _recover_stale_youtube_jobs()
    video = db.get_youtube_video(video_id)
    if not video:
        return jsonify({"error": "not_found"}), 404
    kq = video.get("key_quotes") or "[]"
    try:
        kq_parsed = json.loads(kq) if isinstance(kq, str) else kq
    except Exception:
        kq_parsed = []
    return jsonify({
        "video_id": video_id,
        "status": video.get("status", "unknown"),
        "title": video.get("title"),
        "channel": video.get("channel"),
        "url": video.get("url"),
        "cope_score": video.get("cope_score"),
        "cope_summary": video.get("cope_summary"),
        "scapegoats": video.get("scapegoats"),
        "cope_mechanisms": video.get("cope_mechanisms"),
        "key_quotes": kq_parsed,
        "transcript_length": video.get("transcript_length"),
        "scored_at": video.get("scored_at"),
        "error_msg": video.get("error_msg"),
    })


@app.route("/api/youtube/score", methods=["POST"])
def api_youtube_score():
    """Queue a video for async scoring. Returns 202 immediately."""
[redacted secret-like line]
[redacted secret-like line]
    if not allowed:
        return jsonify({"error": f"Rate limited. Try again in {wait_mins} minutes."}), 429

    from youtube_scorer import extract_video_id as _extract_video_id
    data = request.get_json() or {}
    url = data.get("url", "").strip()
    if not url:
        return jsonify({"error": "No URL provided"}), 400

    video_id = _extract_video_id(url)
    if not video_id:
        return jsonify({"error": "Could not extract a valid YouTube video ID from that URL"}), 400

    # Return cached result immediately if already scored
    existing = db.get_youtube_video(video_id)
    if existing and existing.get("status") == "scored":
        kq = existing.get("key_quotes") or "[]"
        try:
            kq_parsed = json.loads(kq) if isinstance(kq, str) else kq
        except Exception:
            kq_parsed = []
        return jsonify({
            "status": "scored",
            "video_id": video_id,
            "message": "Already scored — result shown below.",
            "cope_score": existing.get("cope_score"),
            "cope_summary": existing.get("cope_summary"),
            "title": existing.get("title"),
            "channel": existing.get("channel"),
            "url": existing.get("url") or f"https://www.youtube.com/watch?v={video_id}",
            "scapegoats": existing.get("scapegoats"),
            "cope_mechanisms": existing.get("cope_mechanisms"),
            "key_quotes": kq_parsed,
            "transcript_length": existing.get("transcript_length"),
        })

    # Queue it (idempotent — won't double-queue)
[redacted secret-like line]
    # A failed row may just have been requeued, or a worker may already have
    # claimed it. Report the current state instead of the pre-enqueue snapshot.
    current = db.get_youtube_video(video_id) or {}
    current_status = current.get("status") or (
        "queued" if queued else (existing or {}).get("status", "queued")
    )

[redacted secret-like line]
    return jsonify({
        "status": current_status,
        "video_id": video_id,
        "message": "Queued for scoring — check back in a few minutes. This page will update automatically.",
    }), 202


# ── Internal endpoints for cc-node-01 worker ─────────────────────────────────

# Liveness breadcrumb for the external worker.
#
# 2026-10-03: the worker wedged inside a network call with no timeout. The
# process stayed alive, so systemd never restarted it, and NOTHING anywhere in
# the estate was watching whether the worker still polled - every check looked
# at queue rows, which only go wrong once somebody submits a video. The outage
# therefore ran for ten days and was only noticed when a user's submission sat
# in 'queued'.
#
# The worker is on a home LAN and cannot be probed from here, but it polls this
# endpoint every 60s, so the poll itself is the heartbeat. Recording when it
# last arrived turns an invisible worker outage into something the estate check
# can see within minutes, with no submission required.
WORKER_POLL_MARKER = os.path.join(
    os.path.dirname(os.path.abspath(__file__)), "data", "worker_last_poll.json"
)


def _record_worker_poll():
    """Stamp the worker's last poll. Best-effort: never breaks the poll."""
    try:
        payload = json.dumps({
            "last_poll_at": datetime.now(timezone.utc).isoformat(),
            "source": "api_internal_queued",
        })
        # Atomic replace via a temp file in the same directory, so a monitor
        # reading concurrently can never see a half-written file, and a crash
        # mid-write cannot leave the marker truncated.
        directory = os.path.dirname(WORKER_POLL_MARKER)
        fd, tmp = tempfile.mkstemp(prefix=".worker-poll-", dir=directory)
        try:
            with os.fdopen(fd, "w", encoding="utf-8") as handle:
                handle.write(payload)
                handle.flush()
                os.fsync(handle.fileno())
            os.replace(tmp, WORKER_POLL_MARKER)
        finally:
            if os.path.exists(tmp):
                os.unlink(tmp)
    except Exception:
        logging.debug("Could not record worker poll marker", exc_info=True)


@app.route("/api/internal/queued")
def api_internal_queued():
[redacted secret-like line]
    if not _worker_auth():
        return jsonify({"error": "unauthorized"}), 401
    _record_worker_poll()
    _recover_stale_youtube_jobs()
    videos = db.get_queued_videos(limit=5)
    return jsonify({"queued": videos})


@app.route("/api/internal/claim/<video_id>", methods=["POST"])
def api_internal_claim(video_id):
    """Worker claims a video (queued → processing) atomically."""
    if not _worker_auth():
        return jsonify({"error": "unauthorized"}), 401
    claimed = db.claim_youtube_video(video_id)
    # ── ATTEMPT_TRAIL_PATCH (2026-10-24) - opening bookend ───────────────────
    if claimed:
        try:
            db.log_youtube_score_attempt(
                video_id, None,
                db.get_youtube_score_attempts(video_id) + 1,
                "started", None,
            )
        except Exception as exc:
            logging.warning("Could not log claim attempt for %s: %s", video_id, exc)
    return jsonify({"claimed": claimed})


@app.route("/api/internal/heartbeat/<video_id>", methods=["POST"])
def api_internal_heartbeat(video_id):
    """Worker renews its lease on a job it still holds.

    Deliberately trivial: touches only lease_renewed_at on a row that is still
    'processing'. It cannot write a score, change provenance or revive a
    terminal row, so a heartbeat arriving after the job was recovered is a
    no-op that returns renewed=false and tells the worker to give up the job.
    """
    if not _worker_auth():
        return jsonify({"error": "unauthorized"}), 401
    renewed = db.renew_youtube_lease(video_id)
    return jsonify({"renewed": renewed})


def _store_transcript(video_id, transcript, title=None, channel=None, *, pending_only=False):
    """Persist the worker's transcript so the extended pass never refetches.

    Also accepts metadata from failed scoring attempts so a successful fetch
    is preserved even when the model returns an invalid result. Best-effort:
    a persistence failure must never prevent the worker callback completing.
    """
    if not isinstance(transcript, str) or not transcript.strip():
        return False
    conn = None
    try:
        import sqlite3 as _sq
        conn = _sq.connect(str(BASE / "data" / "copecheck_uk.db"), timeout=15)
        cols = [r[1] for r in conn.execute("PRAGMA table_info(youtube_videos)")]
        if "transcript" not in cols:
            logging.warning("transcript column missing - skipping transcript persist")
            return False
        fields = ["transcript = ?", "transcript_length = ?"]
        values = [transcript, len(transcript)]
        for column, value in (("title", title), ("channel", channel)):
            if isinstance(value, str) and value.strip() and value.strip().lower() != "unknown":
                fields.append(column + " = ?")
                values.append(value.strip())
        # An old failure may arrive after another attempt has already scored.
        # Apply this guard in the UPDATE so it also covers concurrent callbacks.
        guard = " AND status <> 'scored'" if pending_only else ""
        updated = conn.execute(
            "UPDATE youtube_videos SET " + ", ".join(fields) + " WHERE video_id = ?" + guard,
            values + [video_id],
        )
        conn.commit()
        if updated.rowcount:
            logging.info("Stored transcript for %s (%d chars)", video_id, len(transcript))
        return updated.rowcount > 0
    except Exception as exc:
        logging.warning("Could not store transcript for %s: %s", video_id, exc)
        return False
    finally:
        if conn is not None:
            conn.close()


# ── WORKER ERROR CLASSIFICATION (added 2026-10-24) ───────────────────────────
# Replaces `if "transcript" in worker_error.lower()`. That test decided both
# "is this retryable" and "should recovery run" from one magic substring, so a
# scoring fault - which never contains the word "transcript" - bypassed
# classification and recovery together and was written off as terminal on its
# first occurrence. Rqt9kWoTJbc died that way on
# "Scoring error: Expecting value: line 1 column 958 (char 957)", a truncated
# JSON body from the scoring model and about as transient as a fault gets.
#
# Adding "scoring" as a second substring would reproduce the defect with a
# longer list, so classification here is structured instead:
#
#   * If the worker supplies `stage` and `retryable`, trust them. That is the
#     correct long-term contract and cc-node-01 should be changed to send it;
#     this host cannot currently reach cc-node-01 to do that, so the pattern
#     fallback below stands in until it can.
#   * Otherwise classify by *fault family*, not by keyword: transport faults,
#     model-output faults and resource faults are all retryable; only a
#     positively-established permanent fact about the video is terminal.
#   * An unrecognised error is treated as retryable. Previously the default was
#     terminal, which is the expensive direction to be wrong in: a wrongly
#     retried video costs one more worker pass, a wrongly failed one is lost
#     until someone notices. The attempt cap keeps that bounded.

# Permanent facts about the video. Only these end a job on the first report.
_YT_TERMINAL_PATTERNS = (
    "no transcript available (not retryable)",
    "no captions and no obtainable audio",
    "video unavailable",
    "video is unavailable",
    "private video",
    "members-only",
    "age-restricted",
    "removed by the uploader",
    "copyright",
    "does not exist",
    "invalid video id",
    "could not extract video id",
    "live stream has not started",
    "no audio track",
)

# Transient faults, grouped by family so the intent stays legible.
_YT_RETRYABLE_PATTERNS = (
    # Model-output faults: malformed, truncated or unparseable scoring JSON.
    "scoring error", "scoring failed", "score error", "no result",
    "expecting value", "expecting ','", "expecting ':'", "unterminated",
    "jsondecodeerror", "json decode", "invalid json", "malformed",
    "could not extract fields", "robust_json_parse", "unexpected eof",
    "truncated", "empty response", "no content",
    # Transport faults.
    "timeout", "timed out", "readtimeout", "connecttimeout",
    "connectionerror", "connection reset", "connection refused",
    "connection aborted", "newconnectionerror", "nameresolutionerror",
    "temporary failure in name resolution", "no route to host",
    "network is unreachable", "broken pipe", "ssl", "eof occurred",
    "remote end closed", "chunkedencodingerror", "unreachable",
    # Resource / upstream capacity faults.
    "rate limit", "ratelimit", "429", "too many requests", "quota",
    "overloaded", "capacity", "server error", "500", "502", "503", "504",
    "bad gateway", "service unavailable", "gateway timeout",
    "internal server error", "infrastructure failure (retryable)",
    # Process-level faults on either host.
    "killed", "oom", "out of memory", "worker recycle", "restart",
    "lease expired", "did not claim",
)


def _classify_worker_error(worker_error, worker_data=None):
    """Return (stage, retryable, reason) for a worker-reported failure.

    stage is "transcript", "scoring" or "unknown" and selects the recovery
    strategy; retryable decides whether the job gets another pass at all.
    """
    data = worker_data or {}
    text = str(worker_error or "").lower()

    # 1. Structured verdict from the worker wins outright.
    raw_stage = str(data.get("stage") or "").strip().lower()
    stage = raw_stage if raw_stage in ("transcript", "scoring") else "unknown"
    if isinstance(data.get("retryable"), bool):
        return (stage, bool(data["retryable"]),
                "worker-declared stage=%s retryable=%s" % (stage or "unknown",
                                                           data["retryable"]))

    # 2. Infer the stage when the worker did not name one.
    if stage == "unknown":
        if any(k in text for k in ("scoring", "score ", "minimax", "codex",
                                   "json", "expecting value", "parse")):
            stage = "scoring"
        elif any(k in text for k in ("transcript", "caption", "whisper",
                                     "subtitle", "audio")):
            stage = "transcript"

    # 3. A positively-established permanent fact is terminal.
    for pattern in _YT_TERMINAL_PATTERNS:
        if pattern in text:
            return stage, False, "matched terminal pattern %r" % pattern

    # 4. A recognised transient family is retryable.
    for pattern in _YT_RETRYABLE_PATTERNS:
        if pattern in text:
            return stage, True, "matched retryable pattern %r" % pattern

    # 5. Unknown: retry within the cap rather than discard the video.
    return stage, True, "unclassified error, defaulting to retryable"


def _persist_raw_worker_response(video_id, worker_data, worker_error):
    """Keep the raw scoring payload for a parse failure, on this host.

    The whole reason Rqt9kWoTJbc was hard to diagnose is that the only copy of
    the malformed response lived in the worker's memory on cc-node-01 and was
    gone the moment the POST returned. Anything the worker does send us about a
    scoring fault gets written here so the next occurrence is readable without
    SSH to the worker node - which, with Tailscale logged out, is not currently
    possible at all.
    """
    try:
        raw = None
        for key in ("raw_response", "raw", "response_text", "model_response",
                    "scoring_raw", "raw_output"):
            if worker_data.get(key):
                raw = worker_data[key]
                break
        target_dir = BASE / "logs" / "raw_scoring_failures"
        target_dir.mkdir(parents=True, exist_ok=True)
        stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
        path = target_dir / ("%s-%s.json" % (video_id, stamp))
        # Echo back only the diagnostic fields. Dumping worker_data wholesale
[redacted secret-like line]
        payload = {
            "video_id": video_id,
            "captured_at_utc": stamp,
            "worker_error": str(worker_error)[:4000],
            "stage": worker_data.get("stage"),
            "retryable": worker_data.get("retryable"),
            "title": worker_data.get("title"),
            "channel": worker_data.get("channel"),
            "transcript_length": worker_data.get("transcript_length"),
            "raw_response_present": raw is not None,
            "raw_response": (str(raw)[:200000] if raw is not None else None),
        }
        with open(path, "w", encoding="utf-8") as handle:
            json.dump(payload, handle, ensure_ascii=False, indent=2)
        try:
            os.chmod(path, 0o600)
        except Exception:
            pass
        if raw is None:
            logging.warning(
                "Scoring failure for %s recorded at %s, but the worker sent no "
                "raw response field; cc-node-01 must forward 'raw_response' for "
                "these to be fully diagnosable", video_id, path.name,
            )
        else:
            logging.info("Persisted raw scoring response for %s to %s",
                         video_id, path.name)
        return str(path)
    except Exception as exc:
        logging.warning("Could not persist raw scoring response for %s: %s",
                        video_id, exc)
        return None


def _trigger_extended_oracle(video_id):
    """Fire the three-layer oracle pass for one video, asynchronously.

    Runs as a detached subprocess so it cannot block or time out the worker's
    POST, and cannot be killed by a gunicorn worker recycle. The hourly cron
    remains as a safety net for anything this misses.
    """
    def _spawn():
        try:
            import subprocess
            subprocess.Popen(
                [str(BASE / "venv" / "bin" / "python3"),
                 str(BASE / "oracle_backfill.py"), video_id],
                cwd=str(BASE),
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL,
                start_new_session=True,
            )
            logging.info("Extended oracle pass triggered for %s", video_id)
        except Exception as exc:
            logging.warning("Could not trigger extended pass for %s: %s", video_id, exc)

    try:
        threading.Thread(target=_spawn, name=f"oracle-ext-{video_id}",
                         daemon=True).start()
    except Exception as exc:
        logging.warning("Could not start extended-pass thread for %s: %s", video_id, exc)


@app.route("/api/internal/score-complete", methods=["POST"])
def api_internal_score_complete():
    """Worker delivers scored result here. Stores in DB."""
    if not _worker_auth():
        return jsonify({"error": "unauthorized"}), 401
    data = request.get_json() or {}
    video_id = data.get("video_id", "").strip()
    if not video_id:
        return jsonify({"error": "video_id required"}), 400

    if data.get("error"):
        worker_error = str(data["error"])
        current = db.get_youtube_video(video_id)
        if not current or current.get("status") != "processing":
            # Do not spend budget or replace evidence for duplicate/late
            # callbacks once a row is queued, failed, or already scored.
            return jsonify({"ok": True, "status": "noop"})
        logging.info("YouTube worker reported failure for %s: %s", video_id, worker_error)
        _store_transcript(
            video_id, data.get("transcript"),
            title=data.get("title"), channel=data.get("channel"), pending_only=True,
        )
        # ── Classification-driven routing (2026-10-24) ───────────────────
        # Was: `if "transcript" in worker_error.lower()`. See
        # _classify_worker_error for why a substring test was the defect.
        stage, retryable, reason = _classify_worker_error(worker_error, data)
        logging.info(
            "YouTube failure classified for %s: stage=%s retryable=%s (%s)",
            video_id, stage, retryable, reason,
        )

        # A scoring-stage fault is the one whose evidence vanishes with the
        # worker process, so capture whatever we were sent before deciding.
        if stage == "scoring":
            _persist_raw_worker_response(video_id, data, worker_error)

        # Every transient worker failure returns to the same outbound worker,
        # including transcript timeouts. Starting a Mac recovery thread only
        # proves that a thread launched, not that its proxy is reachable; that
        # old branch bypassed this retry budget when the proxy later failed.
        resolution = db.resolve_youtube_worker_failure(
            video_id, worker_error, stage, retryable, reason,
        )
        if resolution["status"] != "noop":
            outcome = ("exhausted" if resolution["exhausted"] else
                       "retrying" if resolution["status"] == "requeued" else "terminal")
            db.log_youtube_score_attempt(
                video_id, data.get("title"), resolution["attempts"],
                outcome + ":" + stage, worker_error,
            )
            logging.info(
                "YouTube failure resolved for %s: %s (%d/%d attempts)",
                video_id, resolution["status"], resolution["attempts"],
                db.YOUTUBE_MAX_SCORE_ATTEMPTS,
            )
        return jsonify({"ok": True, "stage": stage, **resolution})

    kq = data.get("key_quotes", [])
    key_quotes_str = json.dumps(kq) if isinstance(kq, list) else str(kq)
    db.complete_youtube_video(
        video_id=video_id,
        title=data.get("title", "Unknown"),
        channel=data.get("channel", "Unknown"),
        transcript_length=int(data.get("transcript_length", 0)),
        cope_score=float(data.get("cope_score", 0)),
        cope_summary=data.get("cope_summary", ""),
        scapegoats=data.get("scapegoats", ""),
        cope_mechanisms=data.get("cope_mechanisms", ""),
        key_quotes=key_quotes_str,
        video_summary=data.get("video_summary", ""),
        dt_verdict=data.get("dt_verdict", ""),
        butchers_verdict=data.get("butchers_verdict", ""),
    )
    logging.info("YouTube scored via worker: %s cope=%.1f", video_id, float(data.get("cope_score", 0)))
    # ── ATTEMPT_TRAIL_PATCH (2026-10-24) - closing bookend ───────────────────
    try:
        db.log_youtube_score_attempt(
            video_id, data.get("title"),
            db.get_youtube_score_attempts(video_id) + 1,
            "success", None,
        )
    except Exception as exc:
        logging.warning("Could not log success attempt for %s: %s", video_id, exc)

    # ── Extended (three-layer) oracle pass ───────────────────────────────────
    # The core score above is already committed. Everything below is additive
    # and wrapped so that no failure here can lose or corrupt it.
    try:
        _store_transcript(video_id, data.get("transcript", "") or "")
        already_extended = bool(
            (data.get("video_summary") or "").strip()
            or (data.get("dt_verdict") or "").strip()
            or (data.get("butchers_verdict") or "").strip()
        )
        if not already_extended:
            _trigger_extended_oracle(video_id)
    except Exception as exc:
        logging.warning("Extended oracle step failed for %s (core score intact): %s",
                        video_id, exc)

    return jsonify({"ok": True, "status": "scored"})


# --- Oracle Question Detail ---

@app.route("/ask-oracle/<int:question_id>")
def oracle_question_detail(question_id):
    import sqlite3
    conn = sqlite3.connect(str(BASE / "data" / "copecheck_uk.db"))
    conn.row_factory = sqlite3.Row
    row = conn.execute("SELECT * FROM oracle_questions WHERE id = ?", (question_id,)).fetchone()
    conn.close()
    if not row:
        return "Question not found", 404
    question = dict(row)
    return render_template("oracle_question_detail.html", question=question)



@app.route("/sitemap.xml")
def sitemap():
    from flask import Response
    import sqlite3
    pages = ["", "feed", "data", "labour-market", "youtube", "about", "analyser", "ask-oracle", "scapegoats"]
    figures = db.get_leaderboard()
    xml = '<?xml version="1.0" encoding="UTF-8"?>\n'
    xml += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'
    for p in pages:
        xml += f'  <url><loc>https://uk.copecheck.com/{p}</loc></url>\n'
    for fig in figures:
        xml += f'  <url><loc>https://uk.copecheck.com/figure/{fig["id"]}</loc></url>\n'
    # Analysis detail pages
    try:
        analyses = db.recent_analyses(limit=200)
        for a in analyses:
            if a.get("slug"):
                xml += f'  <url><loc>https://uk.copecheck.com/analysis/{a["slug"]}</loc></url>\n'
    except Exception:
        pass
    # Bulletin detail pages
    try:
        bulletins = db.get_bulletin_analyses(limit=100)
        for b in bulletins:
            if b.get("id"):
                xml += f'  <url><loc>https://uk.copecheck.com/bulletin/{b["id"]}</loc></url>\n'
    except Exception:
        pass
    # YouTube detail pages
    try:
        conn = sqlite3.connect(str(BASE_PATH / "data" / "copecheck_uk.db"))
        conn.row_factory = sqlite3.Row
        videos = conn.execute("SELECT video_id FROM youtube_videos WHERE status = ?", ("scored",)).fetchall()
        for v in videos:
            xml += f'  <url><loc>https://uk.copecheck.com/youtube/{v["video_id"]}</loc></url>\n'
        conn.close()
    except Exception:
        pass
    # Oracle question detail pages
    try:
        questions = db.get_recent_questions(limit=200)
        for q in questions:
            if q.get("id"):
                xml += f'  <url><loc>https://uk.copecheck.com/ask-oracle/{q["id"]}</loc></url>\n'
    except Exception:
        pass
    xml += '</urlset>'
    return Response(xml, mimetype="application/xml")




def _add_to_resend(email, first_name=""):
    """Add subscriber to Resend Cope Report audience."""
    import requests as _resend_req, os as _os
[redacted secret-like line]
    audience_id = "e0c71613-ce4e-4e25-a920-515dfe0a90ff"
[redacted secret-like line]
        return
    try:
        _resend_req.post(
            f"https://api.resend.com/audiences/{audience_id}/contacts",
[redacted secret-like line]
            json={"email": email, "first_name": first_name, "unsubscribed": False},
            timeout=5
        )
    except Exception:
        pass  # Don't fail the main subscription if Resend is down

# --- Newsletter subscribe (Resend) ---
@app.route('/api/subscribe', methods=['POST'])
def api_newsletter_subscribe():
    """Subscribe email to Resend Cope Report audience."""
    import requests as _req, os as _os
    data = request.get_json(silent=True) or {}
    email = data.get('email', '').strip()
    if not email or '@' not in email:
        return jsonify({'success': False, 'message': 'Please enter a valid email address.'}), 400
[redacted secret-like line]
[redacted secret-like line]
        return jsonify({'success': False, 'message': 'Server configuration error.'}), 500
    try:
        r = _req.post(
            'https://api.resend.com/audiences/e0c71613-ce4e-4e25-a920-515dfe0a90ff/contacts',
[redacted secret-like line]
            json={'email': email, 'unsubscribed': False},
            timeout=8
        )
        if r.status_code in (200, 201):
            return jsonify({'success': True, 'message': "You're subscribed!"})
        if r.status_code == 422:
            return jsonify({'success': True, 'message': "Already subscribed — you're good!"})
        return jsonify({'success': False, 'message': 'Something went wrong. Please try again.'}), 500
    except Exception:
        return jsonify({'success': False, 'message': 'Connection error. Please try again.'}), 500



# --- Feedback endpoint ---
@app.route('/api/feedback', methods=['POST'])
def api_feedback():
[redacted secret-like line]
    import json as _json, os as _os, threading
    from datetime import datetime as _dt
    data = request.get_json(silent=True) or {}
    text = data.get('text', '').strip()
    if not text or len(text) > 5000:
        return jsonify({'error': 'Invalid feedback'}), 400
    entry = {
        'text': text,
        'email': data.get('email', '').strip()[:200],
        'page': data.get('page', '')[:500],
        'site': 'uk.copecheck.com',
        'ts': _dt.utcnow().isoformat(),
        'ip': request.remote_addr,
    }
    # Save locally
    fb_dir = _os.path.join(_os.path.dirname(__file__), 'feedback')
    _os.makedirs(fb_dir, exist_ok=True)
    fb_file = _os.path.join(fb_dir, 'feedback.jsonl')
    with open(fb_file, 'a') as f:
        f.write(_json.dumps(entry) + "\n")
[redacted secret-like line]
    def _notify():
        try:
            import requests as _req
[redacted secret-like line]
        except Exception:
            pass
    threading.Thread(target=_notify, daemon=True).start()
    return jsonify({'success': True})



@app.route('/robots.txt')
def robots():
    return "User-agent: *\nAllow: /\n\nSitemap: https://uk.copecheck.com/sitemap.xml\n", 200, {'Content-Type': 'text/plain'}

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    app.run(host="0.0.0.0", port=5002, debug=os.getenv("FLASK_DEBUG") == "1")


# ── Trailing-slash canonicalisation (added 2026-09-26, infra audit) ──
# Flask 404s on "/foo/" when the route is declared as "/foo". This installs a
# before_request hook that 301s the slashed form to the canonical slash-less
# one, but only when the slashed form is not itself a real route. Revert by
# deleting these three lines and slash_canonical.py.
from slash_canonical import install_slash_canonicaliser  # noqa: E402
install_slash_canonicaliser(app)  # noqa: E402
```
