---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\" UK Labour Market Data Fetcher for CopeCheck UK. Sources (in priority order): 1. ONS API — headline vacancies (AP2Y time series) + VACS02 XLSX (by industry) 2. KPMG/REC Report on Jobs —."
resource: "https://uk.copecheck.com"
tags: ["copecheck", "uk", "source-file", "py"]
timestamp: "2026-09-15T12:36:12Z"
site: "uk"
source_path: "copecheck-uk/uk_labour_fetcher.py"
---

# !/usr/bin/env python3

Source path: `copecheck-uk/uk_labour_fetcher.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-09-15T12:36:12Z`

```py
#!/usr/bin/env python3
"""
UK Labour Market Data Fetcher for CopeCheck UK.

Sources (in priority order):
  1. ONS API — headline vacancies (AP2Y time series) + VACS02 XLSX (by industry)
  2. KPMG/REC Report on Jobs — permanent placements, temp billings, staff availability
  3. Adzuna — graduate/entry-level vacancies (Job Market Report page, with graceful fallback)
  4. AI redundancy tracker — seed data

Run: python3 uk_labour_fetcher.py [--seed-only] [--no-rec] [--no-adzuna] [--no-vacs]
"""
import io
import json
import logging
import os
import re
import sqlite3
import sys
import time
from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import urldefrag, urljoin

import requests

try:
    import openpyxl
    HAS_OPENPYXL = True
except ImportError:
    HAS_OPENPYXL = False

try:
    import trafilatura
    HAS_TRAFILATURA = True
except ImportError:
    HAS_TRAFILATURA = False

try:
    from lxml import html as lxml_html
    HAS_LXML = True
except ImportError:
    HAS_LXML = False

log = logging.getLogger("uk_labour_fetcher")
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")

# ──────────────────────────────────────────────────────────────────────────────
# Database path — same DB as main UK site
# ──────────────────────────────────────────────────────────────────────────────
BASE = Path(__file__).parent
DB_PATH = os.environ.get(
    "COPECHECK_UK_DB",
    str(BASE / "data" / "copecheck_uk.db"),
)
Path(DB_PATH).parent.mkdir(parents=True, exist_ok=True)

SCHEMA_ADDITIONS = """
CREATE TABLE IF NOT EXISTS rec_report (
    id              INTEGER PRIMARY KEY AUTOINCREMENT,
    report_month    TEXT UNIQUE NOT NULL,
    perm_index      REAL,
    temp_index      REAL,
    staff_avail_index REAL,
    vacancies_index REAL,
    key_quote       TEXT,
    source_url      TEXT,
    consecutive_months_below_50 INTEGER DEFAULT 0,
    fetched_at      TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_rec_month ON rec_report(report_month DESC);

CREATE TABLE IF NOT EXISTS adzuna_snapshot (
    id                    INTEGER PRIMARY KEY AUTOINCREMENT,
    snapshot_date         TEXT UNIQUE NOT NULL,
    graduate_vacancies    INTEGER,
    graduate_yoy_pct      REAL,
    entry_level_vacancies INTEGER,
    entry_level_yoy_pct   REAL,
    total_vacancies       INTEGER,
    source_url            TEXT,
    fetched_at            TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_adzuna_date ON adzuna_snapshot(snapshot_date DESC);

CREATE TABLE IF NOT EXISTS ai_redundancy_tracker (
    id              INTEGER PRIMARY KEY AUTOINCREMENT,
    company         TEXT NOT NULL,
    sector          TEXT,
    announced_date  TEXT,
    roles_cut       INTEGER,
    ai_cited        INTEGER DEFAULT 1,
    source_url      TEXT,
    classification  TEXT,
    notes           TEXT,
    created_at      TEXT DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(company, announced_date)
);
CREATE INDEX IF NOT EXISTS idx_ai_redundancy_company ON ai_redundancy_tracker(company);

CREATE TABLE IF NOT EXISTS vacs02_snapshot (
    id              INTEGER PRIMARY KEY AUTOINCREMENT,
    snapshot_date   TEXT NOT NULL,
    industry        TEXT NOT NULL,
    vacancies_000s  REAL,
    period_label    TEXT,
    source_url      TEXT,
    fetched_at      TEXT DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(snapshot_date, industry)
);
CREATE INDEX IF NOT EXISTS idx_vacs02_date ON vacs02_snapshot(snapshot_date DESC);
"""

@contextmanager
def db_conn():
    c = sqlite3.connect(DB_PATH, timeout=60)
    c.row_factory = sqlite3.Row
    c.execute("PRAGMA journal_mode=WAL")
    try:
        yield c
        c.commit()
    finally:
        c.close()


def init_tables():
    with db_conn() as c:
        c.executescript(SCHEMA_ADDITIONS)
    log.info("DB tables initialised")


# ──────────────────────────────────────────────────────────────────────────────
# 1. ONS VACS02 — Vacancies by Industry (XLSX download, dynamic filename)
# ──────────────────────────────────────────────────────────────────────────────
VACS02_DATASET_PAGE = (
    "https://www.ons.gov.uk/employmentandlabourmarket/peoplenotinwork"
    "/unemployment/datasets/vacanciesbyindustryvacs02"
)
ONS_BASE = "https://www.ons.gov.uk"

def _find_vacs02_xlsx_url():
    """Scrape the VACS02 dataset page to find the current XLSX download URL."""
    try:
        r = requests.get(VACS02_DATASET_PAGE, timeout=30,
                         headers={"User-Agent": "CopeCheck/1.0 (uk.copecheck.com)"})
        r.raise_for_status()
    except Exception as e:
        log.warning("VACS02 dataset page failed: %s", e)
        return None

    # Find href ending in .xlsx
    m = re.search(r'href="(/file\?uri=[^"]*vacs02[^"]*\.xlsx)"', r.text, re.IGNORECASE)
    if m:
        return ONS_BASE + m.group(1)
    # Broader fallback
    m = re.search(r'href="(/file\?uri=[^"]*\.xlsx)"', r.text, re.IGNORECASE)
    if m:
        return ONS_BASE + m.group(1)
    return None


def fetch_vacs02():
    """Download VACS02 XLSX (ONS) and extract latest period vacancies by industry.

    Sheet 'levels' structure (0-indexed rows):
      Row 3: industry names starting col 2
      Row 5: ONS series codes
      Row 8+: data rows — col 0 = period like "Jan-Mar 2026", col 1 = flag, col 2+ = thousands
    """
    if not HAS_OPENPYXL:
        log.warning("openpyxl not available — cannot parse VACS02 XLSX")
        return []

    xlsx_url = _find_vacs02_xlsx_url()
    if not xlsx_url:
        log.warning("Could not find VACS02 XLSX URL on dataset page")
        return []

    log.info("Downloading VACS02 XLSX from: %s", xlsx_url)
    try:
        r = requests.get(xlsx_url, timeout=60,
                         headers={"User-Agent": "CopeCheck/1.0 (uk.copecheck.com)"})
        r.raise_for_status()
    except Exception as e:
        log.warning("VACS02 XLSX download failed: %s", e)
        return []

    try:
        wb = openpyxl.load_workbook(io.BytesIO(r.content), read_only=True, data_only=True)
    except Exception as e:
        log.warning("VACS02 XLSX parse failed: %s", e)
        return []

    # Use 'levels' sheet (thousands); fall back to first sheet
    sheet_name = "levels" if "levels" in wb.sheetnames else wb.sheetnames[0]
    ws = wb[sheet_name]
    rows = list(ws.iter_rows(values_only=True))
    if not rows:
        log.warning("VACS02: sheet empty")
        return []

    # Industry names are in row 3 (0-indexed), starting at col 2
    header_row = rows[3] if len(rows) > 3 else rows[0]
    industry_names = []
    for cell in header_row[2:]:
        name = _normalise_vacs02_industry(cell)
        industry_names.append(name)

    # Data rows start at row 8. Find the LAST row where col 0 matches a period
    # pattern like "Jan-Mar 2026" or "Feb-Apr 2026"
    period_re = re.compile(r"^[A-Za-z]{3}[- ][A-Za-z]{3}\s+\d{4}")
    last_data_row = None
    period_label = "Unknown"
    for row in reversed(rows[8:]):
        first = str(row[0] or "").strip()
        if period_re.match(first):
            # Make sure at least col 2 has a real number
            try:
                float(str(row[2] or "").strip())
                last_data_row = row
                period_label = first
                break
            except (ValueError, TypeError):
                continue

    if last_data_row is None:
        log.warning("VACS02: could not find last period data row (pattern: Jan-Mar YYYY)")
        return []

    # Key snapshots by the observation period, not by the day the daily
    # fetcher happened to download the workbook.  A fetch-month key created
    # duplicate releases and mixed stale industries when ONS footnote labels
    # changed between downloads.
    snapshot_date = _vacs02_period_end_month(period_label)
    if snapshot_date is None:
        log.warning("VACS02: rejected unparseable observation period %r", period_label)
        return []
    results = []
    for col_offset, industry in enumerate(industry_names):
        if not industry or industry.lower() in ("none", ""):
            continue
        col_idx = col_offset + 2  # data starts at col 2
        raw_val = last_data_row[col_idx] if col_idx < len(last_data_row) else None
        if raw_val is None:
            continue
        try:
            val = float(str(raw_val).strip().replace(",", ""))
        except (ValueError, TypeError):
            continue
        results.append({
            "snapshot_date": snapshot_date,
            "industry": industry[:120],
            "vacancies_000s": val,
            "period_label": period_label,
            "source_url": xlsx_url,
        })

    log.info("VACS02: %d industries for period '%s'", len(results), period_label)
    return results


# Genuine hyphenated prefixes that must survive de-hyphenation.  Anything else
# shaped like "Construc-tion" is a line-break artifact carried over from the
# ONS XLSX header cells, where long labels are hard-wrapped inside the cell.
_REAL_HYPHEN_PREFIXES = frozenset((
    "non", "e", "self", "co", "pre", "post", "sub", "re", "well", "multi",
    "inter", "intra", "long", "short", "full", "part", "high", "low", "mid",
    "cross", "semi", "anti", "ex", "by", "off", "on", "over", "under",
))


def _dehyphenate_vacs02_industry(name):
    """Rejoin words the ONS workbook split across lines ("Manu- facturing")."""
    # A hyphen followed by whitespace is always a line-break artifact: a real
    # compound never has a space after its hyphen.
    name = re.sub(r"(?<=[A-Za-z])-\s+(?=[a-z])", "", name)

    # Hyphen with no space ("Construc-tion"): rejoin unless the left-hand side
    # is a genuine prefix such as "non-financial" or "e-commerce".
    def _join(match):
        left, right = match.group(1), match.group(2)
        if left.lower() in _REAL_HYPHEN_PREFIXES:
            return match.group(0)
        return left + right

    return re.sub(r"\b([A-Za-z]+)-([a-z]+)", _join, name)


def _normalise_vacs02_industry(value):
    """Strip presentation whitespace, line-break hyphens and footnote digits."""
    name = re.sub(r"\s+", " ", str(value or "")).strip()
    name = _dehyphenate_vacs02_industry(name)
    return re.sub(r"(?<=\D)\d+$", "", name).strip()


def _vacs02_period_end_month(period_label):
    """Convert an ONS rolling period such as ``May-Jul 2026`` to ``2026-07``."""
    match = re.fullmatch(
        r"[A-Za-z]{3}[- ]([A-Za-z]{3})\s+(\d{4})",
        str(period_label or "").strip(),
    )
    if not match:
        return None
    try:
        month = datetime.strptime(match.group(1), "%b").month
    except ValueError:
        return None
    return f"{int(match.group(2)):04d}-{month:02d}"


def save_vacs02(rows):
    if not rows:
        return
    snapshot_dates = {row["snapshot_date"] for row in rows}
    if len(snapshot_dates) != 1:
        raise ValueError("VACS02 save requires exactly one observation period")
    snapshot_date = next(iter(snapshot_dates))
    with db_conn() as c:
        # The workbook is a complete snapshot.  Replace that period as one
        # transaction so removed/renamed industries cannot linger beside the
        # current release.
        c.execute("DELETE FROM vacs02_snapshot WHERE snapshot_date = ?", (snapshot_date,))
        for r in rows:
            c.execute("""
                INSERT INTO vacs02_snapshot
                    (snapshot_date, industry, vacancies_000s, period_label, source_url)
                VALUES (?, ?, ?, ?, ?)
                ON CONFLICT(snapshot_date, industry) DO UPDATE SET
                    vacancies_000s=excluded.vacancies_000s,
                    period_label=excluded.period_label,
                    source_url=excluded.source_url,
                    fetched_at=CURRENT_TIMESTAMP
            """, (r["snapshot_date"], r["industry"], r["vacancies_000s"],
                  r["period_label"], r["source_url"]))
    log.info("Saved %d VACS02 rows", len(rows))


# ──────────────────────────────────────────────────────────────────────────────
# 2. KPMG/REC Report on Jobs
# ──────────────────────────────────────────────────────────────────────────────
class SourceUnavailable(RuntimeError):
    """A source could not be reached or answered with a bot challenge.

    Distinct from a source that was reachable but published nothing usable:
    this one means something is genuinely broken and the run should exit 1.
    """


def _require_live_html(response, what):
    """Return response text, or raise if the body is empty / WAF-challenged."""
    waf = response.headers.get("x-amzn-waf-action")
    if waf:
        raise SourceUnavailable(
            f"{what}: blocked by WAF (x-amzn-waf-action={waf}, "
            f"HTTP {response.status_code})"
        )
    text = response.text or ""
    if not text.strip():
        raise SourceUnavailable(
            f"{what}: empty body (HTTP {response.status_code})"
        )
    return text


REC_INDEX_URL = "https://www.rec.uk.com/our-view/reports-jobs"
# Last-known fallback release.  The publication-month freshness guard rejects
# it once it is too old; normal operation discovers the latest URL from index.
KNOWN_LATEST_REC_URL = (
    "https://www.rec.uk.com/our-view/news/press-releases/"
    "[redacted]"
    "amid-greater-market-uncertainty"
)
REC_PRESS_BASE = "https://www.rec.uk.com"

def _find_latest_rec_press_release(index_html):
    """Find the latest Report on Jobs press release URL in page HTML.
    Searches for the URL pattern anywhere in the page, not just href attributes,
    because the REC CMS sometimes embeds URLs in data attributes or JS.
    """
    # Absolute URLs with /press-releases/ path anywhere in page
    candidates = re.findall(
        r'(?:href|data-[a-z-]+|url|link)=["\']?(https?://www\.rec\.uk\.com/our-view/news/press-releases/[^"\' >]{10,})',
        index_html, re.IGNORECASE
    )
    # Also search for the URL pattern without attribute context
    candidates += re.findall(
        r'"(https?://www\.rec\.uk\.com/our-view/news/press-releases/[^"]{10,})"',
        index_html, re.IGNORECASE
    )
    # Deduplicate and strip malformed fragments occasionally emitted by the
    # REC CMS (some hrefs contain a second URL after a '#').  The index is
    # ordered newest first, so preserve DOM order after normalisation.
    seen = set()
    unique = []
    for c in candidates:
        c = urljoin(REC_PRESS_BASE, urldefrag(c)[0])
        if c not in seen:
            seen.add(c)
            unique.append(c)
    for c in unique:
        if re.search(r'report.{0,20}job|job.{0,20}report', c, re.IGNORECASE):
            return c
    if unique:
        return unique[0]

    # Relative press-release links
    rel = re.findall(
        r'["\']?(/our-view/news/press-releases/[^"\' >]{10,})',
        index_html, re.IGNORECASE
    )
    normalised_rel = [urljoin(REC_PRESS_BASE, urldefrag(c)[0]) for c in rel]
    for c in normalised_rel:
        if re.search(r'report.{0,20}job|job.{0,20}report', c, re.IGNORECASE):
            return c
    if normalised_rel:
        return normalised_rel[0]

    return None

def _fetch_rec_homepage_for_latest():
    """Try REC homepage to find the latest Report on Jobs press release URL."""
    headers = {
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0",
        "Accept": "text/html",
    }
    for url in ["https://www.rec.uk.com/", "https://www.rec.uk.com/our-view"]:
        try:
            r = requests.get(url, timeout=20, headers=headers)
            if r.status_code == 200:
                found = _find_latest_rec_press_release(r.text)
                if found:
                    log.info("REC homepage fallback found: %s", found)
                    return found
        except Exception as e:
            log.warning("REC homepage fallback (%s) failed: %s", url, e)
    return None


# ──────────────────────────────────────────────────────────────────────────────
# REC run-length ("consecutive months below 50") extraction
# ──────────────────────────────────────────────────────────────────────────────
# The REC press releases never print PMI index values -- those sit behind the
# paid S&P Global report -- but they do state, in words, how long the
# demand-for-staff series has been contracting.  That run length is the one
# numeric metric the free release exposes, so it is what this column stores.
_TENS_WORDS = {"twenty": 20, "thirty": 30, "forty": 40, "fifty": 50, "sixty": 60}

_UNIT_ORDINALS = {
    "first": 1, "second": 2, "third": 3, "fourth": 4, "fifth": 5,
    "sixth": 6, "seventh": 7, "eighth": 8, "ninth": 9,
}

_ORDINAL_WORDS = {
    "tenth": 10, "eleventh": 11, "twelfth": 12, "thirteenth": 13,
    "fourteenth": 14, "fifteenth": 15, "sixteenth": 16, "seventeenth": 17,
    "eighteenth": 18, "nineteenth": 19, "twentieth": 20, "thirtieth": 30,
    "fortieth": 40, "fiftieth": 50, "sixtieth": 60,
}
_ORDINAL_WORDS.update(_UNIT_ORDINALS)

# Sentences that are actually about demand for staff / vacancies.  Anchoring
# here is the whole point: an earlier metric-agnostic regex matched "a 45-month
# period of decline", which describes *permanent placements* -- a different
# series -- and stored it as the vacancies run length for August 2026.
_DEMAND_SENTENCE_RE = re.compile(
    r"[^.]*\b(?:demand\s+for\s+staff|overall\s+demand|vacanc\w*)\b[^.]*\.",
    re.IGNORECASE,
)

# "for the thirty-fourth month in a row", "for the thirtieth successive month",
# "for the 34th consecutive month".
_RUN_LENGTH_RE = re.compile(
    r"\bfor\s+the\s+"
    r"(\d{1,3}|[a-z]+(?:-[a-z]+)?)"
    r"(?:st|nd|rd|th)?\s*"
    r"(?:successive|consecutive|straight)?\s*"
    r"month",
    re.IGNORECASE,
)

# "a 34-month period of decline", "a 34-month downturn".
_RUN_PERIOD_RE = re.compile(
    r"\b(\d{1,3}|[a-z]+(?:-[a-z]+)?)[-\s]month\s+"
    r"(?:period|downturn|run|sequence|streak)",
    re.IGNORECASE,
)


def _word_to_run_length(raw):
    """'34' / 'thirty-fourth' / 'thirtieth' -> int; anything else -> None."""
    if raw is None:
        return None
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
        return None
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
[redacted secret-like line]
    if m and m.group(2) in _UNIT_ORDINALS:
        return _TENS_WORDS[m.group(1)] + _UNIT_ORDINALS[m.group(2)]
    return None


def _extract_demand_run_length(page_text):
    """Months of continuous decline in demand for staff, or 0 if not published.

    Returns 0 rather than guessing: some months the release simply does not
    state a run length, and a fabricated number is worse than an absent one.
    """
    text = page_text or ""
    for sentence_match in _DEMAND_SENTENCE_RE.finditer(text):
        sentence = sentence_match.group(0)
        for pattern in (_RUN_LENGTH_RE, _RUN_PERIOD_RE):
            for m in pattern.finditer(sentence):
                value = _word_to_run_length(m.group(1))
                if value and 1 <= value <= 200:
                    return value
    return 0


def fetch_rec_report():
    """Scrape the REC Report on Jobs index page then the latest press release."""
    headers = {
        "User-Agent": (
            "Mozilla/5.0 (X11; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0"
        ),
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Accept-Language": "en-GB,en;q=0.9",
    }

    log.info("Fetching REC index: %s", REC_INDEX_URL)
    try:
        r = requests.get(REC_INDEX_URL, timeout=30, headers=headers)
        r.raise_for_status()
        index_html = _require_live_html(r, "REC index")
    except SourceUnavailable:
        raise
    except Exception as e:
        raise SourceUnavailable(f"REC index fetch failed: {e}") from e

    press_url = _find_latest_rec_press_release(index_html)
    if not press_url:
        log.info("REC: index page had no link — trying homepage fallback")
        press_url = _fetch_rec_homepage_for_latest()
    if not press_url:
        log.info("REC: using known latest press release URL as fallback")
        press_url = KNOWN_LATEST_REC_URL
    page_html = index_html
    if press_url == REC_INDEX_URL:
        page_text = index_html
        press_url = KNOWN_LATEST_REC_URL
    else:
        log.info("REC press release: %s", press_url)
        try:
            time.sleep(1)  # polite delay
            r2 = requests.get(press_url, timeout=30, headers=headers)
            r2.raise_for_status()
            page_html = _require_live_html(r2, "REC press release")
        except SourceUnavailable:
            raise
        except Exception as e:
            # Fail loudly.  The index contains snippets and unrelated dates, so
            # we must not fall back to it; and an unreachable source is a hard
            # failure, not a quiet month.
            raise SourceUnavailable(f"REC press release fetch failed: {e}") from e

        # Use trafilatura for clean text extraction
        if HAS_TRAFILATURA:
            page_text = trafilatura.extract(page_html) or ""
            if not page_text:
                # Fallback: strip tags manually
                page_text = re.sub(r"<[^>]+>", " ", page_html)
                page_text = re.sub(r"\s+", " ", page_text)
        else:
            page_text = re.sub(r"<[^>]+>", " ", page_html)
            page_text = re.sub(r"\s+", " ", page_text)

    # ---- Extract key data from text ----
    # Publication metadata is authoritative.  Looking for the first month in
    # article prose produced false dates such as "August 2023" for an August
    # 2026 release because the copy compared current conditions with 2023.
    report_month = _extract_publication_month(page_html, page_text)
    if not report_month or not _report_month_is_current(report_month):
        log.warning("REC: rejected implausible or missing publication month: %r", report_month)
        return None

    perm_idx = _extract_index_near_keyword(page_text, r"permanent\s+(?:staff\s+)?placement")
    temp_idx = _extract_index_near_keyword(page_text, r"temp(?:orary)?\s+(?:staff\s+)?billing")
    staff_idx = _extract_index_near_keyword(page_text, r"staff\s+availab")
    vac_idx = _extract_index_near_keyword(page_text, r"(?:vacanc|permanent\s+vacanc)")

    # Months of unbroken decline in the demand-for-staff (vacancies) series.
    consecutive = _extract_demand_run_length(page_text)

    # Extract key quote
    key_quote = None
    for pattern in [
        r'([A-Z][^.\n]{40,350}(?:consecutive|successive)[^.\n]{0,200}\.)',
        r'([A-Z][^.\n]{40,250}(?:decline|fall|contract|shrink|weaken)[^.\n]{0,150}\.)',
        r'([A-Z][^.\n]{40,250}(?:placement|billing|availab)[^.\n]{0,100}\.)',
    ]:
        m = re.search(pattern, page_text, re.DOTALL)
        if m:
            key_quote = re.sub(r'\s+', ' ', m.group(1)).strip()[:500]
            break

    result = {
        "report_month": report_month,
        "perm_index": perm_idx,
        "temp_index": temp_idx,
        "staff_avail_index": staff_idx,
        "vacancies_index": vac_idx,
        "key_quote": key_quote,
        "source_url": press_url or REC_INDEX_URL,
        "consecutive_months_below_50": consecutive,
    }
    # Never write another all-null/N/A record.  The consecutive-run figure is
    # a valid published metric even where the public release omits PMI values.
    if not any(v is not None for v in (perm_idx, temp_idx, staff_idx, vac_idx)) and consecutive <= 0:
        log.warning("REC: rejected %s because the release exposed no usable metrics", report_month)
        return None
    log.info("REC: month=%s perm=%s temp=%s staff=%s consecutive=%d",
             report_month, perm_idx, temp_idx, staff_idx, consecutive)
    return result


def _extract_month_from_text(text):
    m = re.search(
        r'(January|February|March|April|May|June|July|August|September|October|November|December)'
        r'\s+(202[0-9])',
        text, re.IGNORECASE
    )
    return f"{m.group(1).capitalize()} {m.group(2)}" if m else None


def _extract_publication_month(page_html, page_text=""):
    """Return the press release's own publication month, never a prose date."""
    if page_html:
        # Current REC pages expose this on <time class="title__date">.
        patterns = [
            r'<time\b[^>]*class=["\'][^"\']*title__date[^"\']*["\'][^>]*\bdatetime=["\']([^"\']+)',
            r'<time\b[^>]*\bdatetime=["\']([^"\']+)["\'][^>]*>',
        ]
        for pattern in patterns:
            match = re.search(pattern, page_html, re.IGNORECASE)
            if not match:
                continue
            raw = match.group(1).strip()
            for fmt in (
                "%a, %d %b %Y %H:%M:%S %z",
                "%Y-%m-%dT%H:%M:%S%z",
                "%Y-%m-%d",
            ):
                try:
                    return datetime.strptime(raw, fmt).strftime("%B %Y")
                except ValueError:
                    pass

        # Visible publication date, restricted to the title-date element.
        title_date = re.search(
            r'<time\b[^>]*class=["\'][^"\']*title__date[^"\']*["\'][^>]*>'
            r'\s*(?:\d{1,2}(?:st|nd|rd|th)?\s+)?'
            r'(January|February|March|April|May|June|July|August|September|October|November|December)'
            r'\s+(202[0-9])',
            page_html, re.IGNORECASE,
        )
        if title_date:
            return f"{title_date.group(1).capitalize()} {title_date.group(2)}"

    # Used only for fixture/fallback pages that lack a <time> element.  Prefer
    # an explicit publication phrase rather than the first date in prose.
    published = re.search(
        r'(?:published|press\s+releases?)\s*(?:on|\|)?\s*'
        r'(?:\d{1,2}(?:st|nd|rd|th)?\s+)?'
        r'(January|February|March|April|May|June|July|August|September|October|November|December)'
        r'\s+(202[0-9])',
        page_text, re.IGNORECASE,
    )
    return f"{published.group(1).capitalize()} {published.group(2)}" if published else None


def _report_month_is_current(report_month, now=None, max_age_days=75):
    """Sanity-check a release selected as 'latest' before persisting it."""
    try:
        period = datetime.strptime(report_month, "%B %Y").replace(tzinfo=timezone.utc)
    except (TypeError, ValueError):
        return False
    now = now or datetime.now(timezone.utc)
    # Month precision: compare from the first of each month and allow one week
    # of clock skew/future-dated publication scheduling.
    age_days = (now - period).days
    return -7 <= age_days <= max_age_days


def _extract_index_near_keyword(text, keyword_pattern):
    """Find a PMI-style index (30.0–70.0) within 150 chars of keyword."""
    pattern = keyword_pattern + r'[^0-9]{0,150}?\b((?:3\d|4\d|5\d|6\d)\.\d)\b'
    m = re.search(pattern, text, re.IGNORECASE | re.DOTALL)
    if m:
        try:
            return float(m.group(1))
        except ValueError:
            pass
    # Reverse search: number then keyword
    pattern2 = r'\b((?:3\d|4\d|5\d|6\d)\.\d)\b[^0-9]{0,150}?' + keyword_pattern
    m2 = re.search(pattern2, text, re.IGNORECASE | re.DOTALL)
    if m2:
        try:
            return float(m2.group(1))
        except ValueError:
            pass
    return None


def save_rec_report(data):
    if not data:
        return
    with db_conn() as c:
        c.execute("""
            INSERT INTO rec_report
                (report_month, perm_index, temp_index, staff_avail_index,
                 vacancies_index, key_quote, source_url, consecutive_months_below_50)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ON CONFLICT(report_month) DO UPDATE SET
                perm_index=COALESCE(excluded.perm_index, perm_index),
                temp_index=COALESCE(excluded.temp_index, temp_index),
                staff_avail_index=COALESCE(excluded.staff_avail_index, staff_avail_index),
                vacancies_index=COALESCE(excluded.vacancies_index, vacancies_index),
                key_quote=COALESCE(excluded.key_quote, key_quote),
                source_url=excluded.source_url,
                consecutive_months_below_50=CASE
                    WHEN excluded.consecutive_months_below_50 > 0
                    THEN excluded.consecutive_months_below_50
                    ELSE consecutive_months_below_50 END,
                fetched_at=CURRENT_TIMESTAMP
        """, (
            data["report_month"], data.get("perm_index"),
            data.get("temp_index"), data.get("staff_avail_index"),
            data.get("vacancies_index"), data.get("key_quote"),
            data.get("source_url"), data.get("consecutive_months_below_50", 0),
        ))
    log.info("Saved REC report for %s", data["report_month"])


# ──────────────────────────────────────────────────────────────────────────────
# 3. Adzuna — archived until a reproducible public source is configured
# ──────────────────────────────────────────────────────────────────────────────
ADZUNA_URLS = [
    "https://www.adzuna.co.uk/stats",
]
ADZUNA_ENABLED = os.environ.get("COPECHECK_ADZUNA_ENABLED", "").strip().lower() in {
    "1", "true", "yes",
}

def fetch_adzuna(max_retries=2):
    """Try an explicitly enabled replacement source; disabled by default."""
    if not ADZUNA_ENABLED:
        log.info("Adzuna refresh disabled: no reproducible public report source is configured")
        return None
    headers = {
        "User-Agent": (
            "Mozilla/5.0 (X11; Linux x86_64; rv:121.0) Gecko/20100101 Firefox/121.0"
        ),
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Accept-Language": "en-GB,en;q=0.9",
        "Accept-Encoding": "gzip, deflate, br",
        "DNT": "1",
    }

    page_text = None
    source_url = ADZUNA_URLS[0]

    for url in ADZUNA_URLS:
        for attempt in range(max_retries):
            try:
                if attempt > 0:
                    time.sleep(3 + attempt * 2)
                r = requests.get(url, timeout=30, headers=headers, allow_redirects=True)
                if r.status_code == 429:
                    log.info("Adzuna rate limited (429) on %s attempt %d", url, attempt + 1)
                    continue
                if r.status_code == 200:
                    page_text = r.text
                    source_url = url
                    break
                log.warning("Adzuna %s: HTTP %d", url, r.status_code)
            except Exception as e:
                log.warning("Adzuna fetch error (%s): %s", url, e)
        if page_text:
            break

    if not page_text:
        log.info("Adzuna: all fetch attempts failed — seeded data remains available")
        return None

    # Use trafilatura for clean text if available
    if HAS_TRAFILATURA:
        clean_text = trafilatura.extract(page_text) or page_text
    else:
        clean_text = re.sub(r"<[^>]+>", " ", page_text)
        clean_text = re.sub(r"\s+", " ", clean_text)

    grad_vacancies = None
    grad_yoy = None
    entry_vacancies = None
    entry_yoy = None
    total_vacancies = None

    # Graduate vacancies count
    for pattern in [
        r'([\d,]+)\s+graduate\s+(?:vacanc|job|role|position)',
        r'graduate\s+(?:vacanc|job)[^\d]{0,60}([\d,]+)',
        r'([\d,]+)\s+(?:open|live|active)\s+graduate',
    ]:
        m = re.search(pattern, clean_text, re.IGNORECASE)
        if m:
            try:
                grad_vacancies = int(m.group(1).replace(",", ""))
                break
            except ValueError:
                pass

    # Graduate YoY
    for pattern in [
        r'graduate[^%]{0,200}?(\-?\d+\.?\d*)\s*%\s*(?:year[- ]on[- ]year|YoY|annual|y\/y)',
        r'(\-?\d+\.?\d*)\s*%[^%]{0,100}graduate',
    ]:
        m = re.search(pattern, clean_text, re.IGNORECASE)
        if m:
            try:
                grad_yoy = float(m.group(1))
                break
            except ValueError:
                pass

    # Entry-level
    for pattern in [
        r'([\d,]+)\s+entry[- ]level\s+(?:vacanc|job|role)',
        r'entry[- ]level\s+(?:vacanc|job)[^\d]{0,60}([\d,]+)',
    ]:
        m = re.search(pattern, clean_text, re.IGNORECASE)
        if m:
            try:
                entry_vacancies = int(m.group(1).replace(",", ""))
                break
            except ValueError:
                pass

    # Total vacancies
    for pattern in [
        r'([\d,]+)\s+(?:total|live|active)\s+(?:vacanc|job)',
        r'(?:total|all)\s+vacanc[^\d]{0,30}([\d,]{4,})',
    ]:
        m = re.search(pattern, clean_text, re.IGNORECASE)
        if m:
            try:
                total_vacancies = int(m.group(1).replace(",", ""))
                break
            except ValueError:
                pass

    if grad_vacancies is None and entry_vacancies is None and total_vacancies is None:
        log.info("Adzuna: page loaded but could not extract vacancy numbers (likely JS-rendered)")
        return None

    snapshot_date = datetime.now(timezone.utc).strftime("%Y-%m")
    result = {
        "snapshot_date": snapshot_date,
        "graduate_vacancies": grad_vacancies,
        "graduate_yoy_pct": grad_yoy,
        "entry_level_vacancies": entry_vacancies,
        "entry_level_yoy_pct": entry_yoy,
        "total_vacancies": total_vacancies,
        "source_url": source_url,
    }
    log.info("Adzuna: grad=%s (%.1f%% YoY), entry=%s, total=%s",
             grad_vacancies, grad_yoy or 0, entry_vacancies, total_vacancies)
    return result


def seed_adzuna_known():
    """Seed known Adzuna data points from the briefing."""
    log.info("Seeding known Adzuna data ...")
    with db_conn() as c:
        c.execute("""
            INSERT INTO adzuna_snapshot
                (snapshot_date, graduate_vacancies, graduate_yoy_pct,
                 entry_level_vacancies, source_url)
            VALUES (?, ?, ?, ?, ?)
            ON CONFLICT(snapshot_date) DO NOTHING
        """, (
            "2026-03", 10667, -34.9, None,
            None,
        ))
    log.info("Seeded Adzuna March 2026")


def save_adzuna(data):
    if not data:
        return
    with db_conn() as c:
        c.execute("""
            INSERT INTO adzuna_snapshot
                (snapshot_date, graduate_vacancies, graduate_yoy_pct,
                 entry_level_vacancies, entry_level_yoy_pct,
                 total_vacancies, source_url)
            VALUES (?, ?, ?, ?, ?, ?, ?)
            ON CONFLICT(snapshot_date) DO UPDATE SET
                graduate_vacancies=COALESCE(excluded.graduate_vacancies, graduate_vacancies),
                graduate_yoy_pct=COALESCE(excluded.graduate_yoy_pct, graduate_yoy_pct),
                entry_level_vacancies=COALESCE(excluded.entry_level_vacancies, entry_level_vacancies),
                entry_level_yoy_pct=COALESCE(excluded.entry_level_yoy_pct, entry_level_yoy_pct),
                total_vacancies=COALESCE(excluded.total_vacancies, total_vacancies),
                source_url=excluded.source_url,
                fetched_at=CURRENT_TIMESTAMP
        """, (
            data["snapshot_date"],
            data.get("graduate_vacancies"),
            data.get("graduate_yoy_pct"),
            data.get("entry_level_vacancies"),
            data.get("entry_level_yoy_pct"),
            data.get("total_vacancies"),
            data.get("source_url"),
        ))
    log.info("Saved Adzuna snapshot %s", data["snapshot_date"])


# ──────────────────────────────────────────────────────────────────────────────
# 4. AI Redundancy Tracker
# ──────────────────────────────────────────────────────────────────────────────
# The previous ten-row seed used placeholder/non-resolving article URLs and
# mixed announced restructuring totals with claims of AI causation.  It has
# been withdrawn.  New rows must be added only from a checked source ledger.
AI_REDUNDANCY_SEED = []


def seed_ai_tracker():
    log.info("Seeding AI redundancy tracker with %d entries ...", len(AI_REDUNDANCY_SEED))
    with db_conn() as c:
        for row in AI_REDUNDANCY_SEED:
            c.execute("""
                INSERT INTO ai_redundancy_tracker
                    (company, sector, announced_date, roles_cut, ai_cited,
                     source_url, classification, notes)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                ON CONFLICT(company, announced_date) DO NOTHING
            """, (
                row["company"], row["sector"], row["announced_date"],
                row["roles_cut"], 1 if row["ai_cited"] else 0,
                row["source_url"], row["classification"], row["notes"],
            ))
    log.info("AI redundancy seed complete")


# ──────────────────────────────────────────────────────────────────────────────
# DB query helpers — used by app.py routes
# ──────────────────────────────────────────────────────────────────────────────
def get_latest_rec_report():
    with db_conn() as c:
        row = c.execute(
            """
            SELECT * FROM rec_report
            WHERE perm_index IS NOT NULL
               OR temp_index IS NOT NULL
               OR staff_avail_index IS NOT NULL
               OR vacancies_index IS NOT NULL
               OR consecutive_months_below_50 > 0
            ORDER BY
              CAST(substr(report_month, -4) AS INTEGER) DESC,
              CASE substr(report_month, 1, instr(report_month, ' ') - 1)
                WHEN 'January' THEN 1 WHEN 'February' THEN 2 WHEN 'March' THEN 3
                WHEN 'April' THEN 4 WHEN 'May' THEN 5 WHEN 'June' THEN 6
                WHEN 'July' THEN 7 WHEN 'August' THEN 8 WHEN 'September' THEN 9
                WHEN 'October' THEN 10 WHEN 'November' THEN 11 WHEN 'December' THEN 12
                ELSE 0 END DESC,
              id DESC
            LIMIT 1
            """
        ).fetchone()
        return dict(row) if row else None


def get_rec_history(limit=12):
    with db_conn() as c:
        rows = c.execute(
            """
            SELECT * FROM rec_report
            WHERE perm_index IS NOT NULL
               OR temp_index IS NOT NULL
               OR staff_avail_index IS NOT NULL
               OR vacancies_index IS NOT NULL
               OR consecutive_months_below_50 > 0
            ORDER BY
              CAST(substr(report_month, -4) AS INTEGER) DESC,
              CASE substr(report_month, 1, instr(report_month, ' ') - 1)
                WHEN 'January' THEN 1 WHEN 'February' THEN 2 WHEN 'March' THEN 3
                WHEN 'April' THEN 4 WHEN 'May' THEN 5 WHEN 'June' THEN 6
                WHEN 'July' THEN 7 WHEN 'August' THEN 8 WHEN 'September' THEN 9
                WHEN 'October' THEN 10 WHEN 'November' THEN 11 WHEN 'December' THEN 12
                ELSE 0 END DESC,
              id DESC
            LIMIT ?
            """, (limit,)
        ).fetchall()
        return [dict(r) for r in rows]


def get_latest_adzuna():
    with db_conn() as c:
        row = c.execute(
            "SELECT * FROM adzuna_snapshot ORDER BY snapshot_date DESC LIMIT 1"
        ).fetchone()
        return dict(row) if row else None


def get_adzuna_history(limit=12):
    with db_conn() as c:
        rows = c.execute(
            "SELECT * FROM adzuna_snapshot ORDER BY snapshot_date DESC LIMIT ?", (limit,)
        ).fetchall()
        return [dict(r) for r in rows]


def get_ai_redundancy_tracker():
    with db_conn() as c:
        rows = c.execute("""
            SELECT * FROM ai_redundancy_tracker
            ORDER BY announced_date DESC, roles_cut DESC
        """).fetchall()
        return [dict(r) for r in rows]


def get_latest_vacs02():
    with db_conn() as c:
        rows = [dict(row) for row in c.execute(
            "SELECT * FROM vacs02_snapshot ORDER BY fetched_at DESC, id DESC"
        ).fetchall()]
    valid = [
        (period, row)
        for row in rows
        if (period := _vacs02_period_end_month(row.get("period_label"))) is not None
    ]
    if not valid:
        return []
    latest_period = max(period for period, _ in valid)
    # Legacy rows used the fetch month as snapshot_date.  Until the cleanup
    # migration runs, deduplicate repeated copies of the latest observation by
    # the normalised industry name and keep the most recently fetched copy.
    latest_by_industry = {}
    for period, row in valid:
        if period != latest_period:
            continue
        industry = _normalise_vacs02_industry(row.get("industry"))
        if industry and industry not in latest_by_industry:
            row["industry"] = industry
            row["snapshot_date"] = period
            latest_by_industry[industry] = row
    return sorted(
        latest_by_industry.values(),
        key=lambda row: row.get("vacancies_000s") or 0,
        reverse=True,
    )


# ──────────────────────────────────────────────────────────────────────────────
# Main runner
# ──────────────────────────────────────────────────────────────────────────────
# Per-source outcome codes.
OK = "ok"            # fetched and saved
EMPTY = "empty"      # source reachable, but published nothing usable
FAILED = "failed"    # hard error: unreachable, or fetch/save raised


def _run_source(name, fetch, save, empty_is_failure=False):
    """Run one source in isolation so its outcome cannot affect the others.

    Returns (status, detail).  Sources are deliberately independent: REC
    publishing nothing usable this month is normal and must not mask, or be
    masked by, a genuine ONS breakage.
    """
    try:
        data = fetch()
    except Exception as exc:  # noqa: BLE001 - isolation is the point
        log.exception("%s: fetch raised", name)
        return (FAILED, f"fetch raised: {exc}")

    if not data:
        if empty_is_failure:
            log.warning("%s: returned no data (expected data every run)", name)
            return (FAILED, "no data returned")
        log.info("%s: nothing new published this run", name)
        return (EMPTY, "nothing new published")

    try:
        save(data)
    except Exception as exc:  # noqa: BLE001
        log.exception("%s: save raised", name)
        return (FAILED, f"save raised: {exc}")

    return (OK, "")


def run_all(seed_ai=True, fetch_vacs02_data=True, fetch_rec=True, fetch_adzuna_data=True):
    init_tables()
    results = {}

    if seed_ai:
        seed_ai_tracker()
        seed_adzuna_known()

    if fetch_vacs02_data:
        # ONS publishes VACS02 every month; an empty result means our parser
        # broke, not that there is nothing to report.
        results["ONS VACS02"] = _run_source(
            "ONS VACS02", fetch_vacs02, save_vacs02, empty_is_failure=True
        )

    if fetch_rec:
        # A month where the free release exposes no usable metric is normal.
        results["REC Report on Jobs"] = _run_source(
            "REC Report on Jobs", fetch_rec_report, save_rec_report
        )

    if fetch_adzuna_data:
        # Deliberately archived: no reproducible public endpoint exists.
        results["Adzuna"] = _run_source(
            "Adzuna", fetch_adzuna, save_adzuna, empty_is_failure=ADZUNA_ENABLED
        )

    for name in sorted(results):
        status, detail = results[name]
        log.info("source %-20s %s%s", name, status, f" — {detail}" if detail else "")

    failed = sorted(n for n, (s, _) in results.items() if s == FAILED)
    if failed:
        log.error("uk_labour_fetcher: hard source failures: %s", ", ".join(failed))
    else:
        log.info("uk_labour_fetcher: run complete — no hard failures")
    return results


def main(argv=None):
    argv = list(sys.argv[1:] if argv is None else argv)
    seed_only = "--seed-only" in argv
    results = run_all(
        seed_ai=True,
        fetch_vacs02_data=not (seed_only or "--no-vacs" in argv),
        fetch_rec=not (seed_only or "--no-rec" in argv),
        fetch_adzuna_data=not (seed_only or "--no-adzuna" in argv),
    )
    # Exit non-zero only for genuine breakage, so a red run actually means
    # something needs looking at.
    return 1 if any(s == FAILED for s, _ in results.values()) else 0


if __name__ == "__main__":
    raise SystemExit(main())
```
