GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / automation/news

Pipeline Headlines and 1 more file

A Python command-line tool in the news folder of GlobalGrid2050 that fetches pipeline feeds, the Renewable Energy Planning Database (REPD) register, solar and wind, using SHA-256.

700 lines of Python from globalgrid2050, in 2 files. Topic: Electricity markets and data pipelines. Section 785 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. News Algorithm transform · globalgrid2050 / automation/news/news_algorithm.py lines 1–238
  2. Pipeline Headlines energy-data · globalgrid2050 / automation/news/pipeline_headlines.py lines 1–462

News Algorithm

A Python module in the automation folder of GlobalGrid2050 that ranks headlines (`rank_headlines`), using SHA-256. It is built from the public URL helper (`public_url`) and the key step (`key`).

transformglobalgrid2050 / automation/news/news_algorithm.py · lines 1–238 of 238 · pattern public_url (shared by 2 files)

What it does
It calculates its inputs. Defines 9 functions or classes, including _under, public_url, _clock, _publication, _policies. Uses libraries __future__, copy, datetime, hashlib, ipaddress.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Downstream impact
Used directly by 4 files: Build News Priority (globalgrid2050); Compare Legacy Collector (globalgrid2050); Test Cop31 Climate Priority (globalgrid2050); Test News Algorithm (globalgrid2050). Reached from 4 other entry points, including GlobalGrid2050 Pipeline Headlines Workflow (globalgrid2050); GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Deterministic headline selection; no collection, project binding or publication.
Why it matters
Imported by Build News Priority. Checked by 3 tests, including Compare Legacy Collector.
Application
globalgrid2050 · automation/news · Python module
Uses
Pipeline Headlines (import), __future__, copy, datetime, hashlib, ipaddress, json, re, urllib.parse
Used by
imported by Build News Priority (import), run by Compare Legacy Collector (script call), imported by Test Cop31 Climate Priority (import), imported by Test News Algorithm (import)
Produces
public_url, rank_headlines
Defines here
_under, public_url, _clock, _publication, _policies, _originality, _source, rank_headlines, key
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/news_algorithm.py:1-238 · blob a58270a1d4875d760a47929a0b013dd3ae12bff2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Deterministic headline selection; no collection, project binding or publication.

Publisher credit survives ranking. Primary-source preference, topic, freshness,
reviewed original reporting and display diversity are separate explanations.
The caller supplies the clock and any source/originality review receipts.
"""
from __future__ import annotations

import copy
import datetime as dt
import hashlib
import ipaddress
import json
import re
from urllib.parse import urlsplit

from automation.news import pipeline_headlines as P

SCHEMA = "globalgrid2050.news.editorial-priority.v1"
PROFILE = {
    "id": "uk-transition-global-context.v1",
    "topic": {"solar": 20, "storage": 20, "grid": 20, "datacentre": 20,
              "wind": 10, "renewables": 10},
    "authority": {"government": 18, "regulator": 18, "institution": 16,
                  "listed_parent": 14, "reporting": 8, "discovery": 2},
    "actionability": 8, "original_reporting": 6, "freshness": 10, "uk_context": 5,
    "freshness_half_life_days": 14, "current_days": 120,
    "publisher_diversity_penalty": 8,
}
PROFILE_SHA256 = hashlib.sha256(json.dumps(PROFILE, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
_GOV_SUFFIXES = ("gov.uk", "gov.scot", "gov.wales", "gov")
_DISCOVERY = ("bloomberg.com", "ft.com")
_DNS_LABEL = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\Z")
_GENRE = re.compile(r"(?:^|/)(?:whitepapers?|webinars?|sponsored)(?:/|$)", re.I)
_UK_CONTEXT = re.compile(r"\b(?:UK|U\.K\.|Britain|British|England|Scotland|Scottish|(?<!New South )Wales|Welsh|Northern Ireland|London|Ofgem|NESO)\b", re.I)


def _under(host, suffix):
    return host == suffix or host.endswith("." + suffix)


def public_url(value):
    """Public DNS HTTPS article URL, without resolving or fetching anything."""
    if not isinstance(value, str) or any(ord(c) < 33 for c in value) or "\\" in value:
        raise ValueError("invalid article URL")
    try:
        raw = urlsplit(value)
        host = (raw.hostname or "").lower().rstrip(".")
        if raw.scheme not in ("http", "https") or raw.username or raw.password or raw.port not in (None, 80, 443):
            raise ValueError("unsafe article URL")
        labels = host.split(".")
        if len(labels) < 2 or any(not _DNS_LABEL.fullmatch(label) for label in labels):
            raise ValueError("public DNS hostname required")
        # Browser numeric aliases (127.1, 2130706433, 0x7f000001) are not DNS names.
        if labels[-1].isdigit() or labels[-1].startswith("0x") or host.endswith((".localhost", ".local", ".internal")):
            raise ValueError("numeric or local hostname")
        try:
            ipaddress.ip_address(host)
        except ValueError:
            pass
        else:
            raise ValueError("IP literal is not an article publisher")
        url = P.D.canonical_link(value)
        if not url:
            raise ValueError("invalid article URL")
        parsed = urlsplit(url)
        return parsed._replace(netloc=host).geturl()
    except (TypeError, ValueError) as exc:
        raise ValueError("invalid public article URL") from exc


def _clock(value):
    try:
        when = dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
    except (AttributeError, TypeError, ValueError) as exc:
        raise ValueError("as_of must be an explicit timezone-aware timestamp") from exc
    if when.tzinfo is None:
        raise ValueError("as_of must be timezone-aware")
    return when.astimezone(dt.timezone.utc)


def _publication(raw, as_of):
    if raw is None or raw == "":
        return {"precision": "unknown", "age_days": None, "state": "unknown", "points": 0}
    if not isinstance(raw, str):
        raise ValueError("publication date must be text or null")
    if re.fullmatch(r"\d{4}-\d{2}-\d{2}", raw):
        try:
            day = dt.date.fromisoformat(raw)
        except ValueError as exc:
            raise ValueError("invalid publication day") from exc
        age, precision = (as_of.date() - day).days, "day"
    else:
        parsed = P.D.parse_date(raw)
        if not parsed:
            return {"precision": "unknown", "age_days": None, "state": "unknown", "points": 0}
        age, precision = (as_of - _clock(parsed)).total_seconds() / 86400, "second"
    if age < 0:
        return {"precision": precision, "age_days": round(age, 4), "state": "future", "points": 0}
    points = round(10 / (1 + age / PROFILE["freshness_half_life_days"]), 2)
    return {"precision": precision, "age_days": round(age, 4),
            "state": "current" if age <= PROFILE["current_days"] else "stale", "points": points}


def _policies(policies):
    by_host = {}
    for policy in policies:
        kind = policy.get("kind")
        if kind not in PROFILE["authority"]:
            raise ValueError("unknown source policy kind")
        if policy.get("access", "unknown") not in ("open", "paywalled", "unknown"):
            raise ValueError("unknown source access policy")
        public_url(policy.get("review_url"))
        hosts = policy.get("hosts")
        if not isinstance(hosts, list) or not hosts or not policy.get("source_id"):
            raise ValueError("source policy requires hosts and source_id")
        if kind == "listed_parent":
            if not policy.get("listed_parent_id"):
                raise ValueError("listed-parent identity required")
            public_url(policy.get("listing_evidence_url"))
        for host in hosts:
            if not isinstance(host, str) or host != urlsplit(public_url("https://" + host + "/")).hostname:
                raise ValueError("source policy hosts must be canonical DNS names")
            if host in by_host:
                raise ValueError("duplicate source policy host")
            by_host[host] = copy.deepcopy(policy)
    return by_host


def _originality(reviews):
    by_url = {}
    for review in reviews:
        url = public_url(review.get("article_url"))
        if review.get("kind") != "original_reporting" or review.get("reviewed") is not True:
            raise ValueError("original reporting requires an explicit reviewed receipt")
        if not isinstance(review.get("basis"), str) or not review["basis"].strip() or len(review["basis"]) > 500:
            raise ValueError("originality receipt needs a bounded review basis")
        public_url(review.get("review_url"))
        if url in by_url:
            raise ValueError("duplicate originality review")
        by_url[url] = copy.deepcopy(review)
    return by_url


def _source(host, policy):
    discovery = next((name for name in _DISCOVERY if _under(host, name)), None)
    if policy:
        kind = policy["kind"]
        group = policy.get("publisher_group") or policy["source_id"]
        basis = {"type": "supplied_source_policy", "review_url": policy["review_url"]}
    else:
        kind = "government" if any(_under(host, suffix) for suffix in _GOV_SUFFIXES) else "reporting"
        if discovery:
            kind = "discovery"
        group = discovery or ("bbc" if any(_under(host, s) for s in ("bbc.co.uk", "bbc.com", "bbci.co.uk")) else host.removeprefix("www."))
        basis = {"type": "hostname_classification", "review_url": None}
    if not isinstance(group, str) or not group.strip():
        raise ValueError("publisher display group must be nonempty text")
    access = policy.get("access", "unknown") if policy else "unknown"
    return {"kind": kind, "display_group": group, "basis": basis, "access": access,
            "access_notice": "May require a subscription; use accessible primary follow-up" if discovery or access == "paywalled" else None,
            "rights_approval": "not_assessed_by_ranking"}


def rank_headlines(items, *, as_of, source_policies=(), originality=(), diversity_penalty=8):
    """Return credited headline metadata and a deterministic, explainable order.

    The soft publisher penalty is for display variety, never source independence.
    An original-reporting receipt is a caller review assertion, not verification.
    No title numbers, possible matches or source brands establish project facts.
    """
    now, policies, reviews = _clock(as_of), _policies(source_policies), _originality(originality)
    if type(diversity_penalty) not in (int, float) or not 0 <= diversity_penalty <= 30:
        raise ValueError("diversity_penalty must be between 0 and 30")
    if not isinstance(items, list) or len(items) > 10000:
        raise ValueError("bounded list of headline items required")
    candidates, urls = [], set()
    for item in items:
        if not isinstance(item, dict) or not isinstance(item.get("title"), str) or not item["title"].strip():
            raise ValueError("headline title required")
        url = public_url(item.get("link"))
        if url in urls:
            raise ValueError("duplicate canonical URL: merge article records before ranking")
        urls.add(url)
        host = urlsplit(url).hostname
        title = P.D.clean_text(item["title"], 300)
        topics = [] if P.EXCLUDE.search(title) else P.topics_of(title)
        climate_level = P.climate_policy_priority(title)
        topic_points = max((PROFILE["topic"][t] for t in topics), default=0)
        category = P.category_of(title) if topics or climate_level else None
        context_only = bool(_GENRE.search(urlsplit(url).path) or P.D.SPONSORED_RE.search(title) or P.BRANDED.search(title))
        source = _source(host, policies.get(host))
        freshness = _publication(item.get("date"), now)
        review = reviews.get(url)
        components = {
            "topic": topic_points,
            "primary_source_preference": PROFILE["authority"][source["kind"]],
            "headline_event_cue": PROFILE["actionability"] if category and not context_only else 0,
            "uk_headline_context": PROFILE["uk_context"] if _UK_CONTEXT.search(title) and topics else 0,
            "publication_freshness": freshness["points"],
            "reviewed_original_reporting": PROFILE["original_reporting"] if review else 0,
        }
        # Irrelevant, promotional and future-dated items stay available as
        # context; display diversity never pushes them ahead of current topics.
        # Existing v1 signed weight profile remains byte-identical for published UI.
        # COP31 and other substantive COP coverage receive an explicit priority
        # ordering bucket, never a fabricated source/evidence/REPD association.
        current_policy = not context_only and freshness["state"] not in ("stale", "future")
        bucket = (-2 if climate_level == 2 else -1 if climate_level == 1 else
                  0 if topics else 1) if current_policy else 1
        metadata = {field: copy.deepcopy(item.get(field)) for field in P.ITEM_FIELDS}
        metadata.update(title=title, link=url)
        metadata["editorial"] = {
            "role": "discovery_lead" if source["kind"] == "discovery" else "primary_context" if source["kind"] in ("government", "regulator", "institution", "listed_parent") else "attributed_reporting",
            "topics": topics, "category_hint": category, "source": source, "freshness": freshness,
            "originality_review": review, "components": components, "base_score": round(sum(components.values()), 2),
            "context_bucket": bucket, "project_fact_status": "NOT_ASSESSED", "verification_status": "NOT_VERIFIED",
            "requires_primary_followup": source["kind"] in ("discovery", "reporting"),
        }
        candidates.append(metadata)
    selected, count = [], {}
    while candidates:
        def key(item):
            e = item["editorial"]
            penalty = diversity_penalty * count.get(e["source"]["display_group"], 0)
            return (e["context_bucket"], -(e["base_score"] - penalty), item["link"])
        picked = min(candidates, key=key)
        candidates.remove(picked)
        e, group = picked["editorial"], picked["editorial"]["source"]["display_group"]
        e["publisher_repetition_penalty"] = diversity_penalty * count.get(group, 0)
        e["selection_score"] = round(e["base_score"] - e["publisher_repetition_penalty"], 2)
        e["rank"] = len(selected) + 1
        count[group] = count.get(group, 0) + 1
        selected.append(picked)
    return {"schema": SCHEMA, "profile_id": PROFILE["id"], "profile_sha256": PROFILE_SHA256,
            "as_of": now.isoformat().replace("+00:00", "Z"), "diversity_penalty": diversity_penalty,
            "input_count": len(items), "items": selected,
            "scope": "Editorial research order only; no source-rights grant, project binding, financial figure extraction or VERIFIED claim."}

Pipeline Headlines

A Python command-line tool in the news folder of GlobalGrid2050 that fetches pipeline feeds, the Renewable Energy Planning Database (REPD) register, solar and wind, using SHA-256.

energy-dataglobalgrid2050 / automation/news/pipeline_headlines.py · lines 1–462 of 788 · Entry point · pattern category_of (shared by 2 files)

What it does
It fetches pipeline feeds, the REPD register, solar and wind. Defines 32 functions or classes, including excluded_publisher, _rx, climate_policy_priority, lane_label, topics_of. Uses libraries __future__, argparse, csv, datetime, io. Side effects: reads or writes files; makes network requests; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register, solar, wind.
Inputs & outputs
In: JSON file pipeline_headlines.json; JSON file pipeline_feeds.json; command-line arguments.
Downstream impact
Used directly by 9 files: News Algorithm (globalgrid2050); Trade (globalgrid2050); Compare Legacy Collector (globalgrid2050); Test Agent7 Dedupe Regressions (globalgrid2050); and 5 more. Reached from 8 other entry points, including GlobalGrid2050 Agent7 V922 CI Workflow (globalgrid2050); GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It loads feeds (`load_feeds`) and is built from the excluded publisher helper (`excluded_publisher`) and the climate policy priority helper (`climate_policy_priority`). Fresh UK renewables, storage, grid and data-centre headlines for Pipeline News. It accepts `--out`, `--feeds` and `--repd`.
Why it matters
Imported by News Algorithm and Trade. Run by GlobalGrid2050 Pipeline Headlines Workflow. Checked by 6 tests, including Compare Legacy Collector.
Application
globalgrid2050 · automation/news · Python CLI
Uses
Datacentre Feed (import), Names (import), Research Indexes (import), __future__, argparse, csv, datetime, io, json, re, sys
Used by
imported by News Algorithm (import), imported by Trade (sys.path import), run by Compare Legacy Collector (script call), imported by Test Agent7 Dedupe Regressions (sys.path import), imported by Test Cop31 Climate Priority (sys.path import), imported by Test Pipeline Headlines (sys.path import), imported by Test Research Context (sys.path import), imported by Test Spp Excluded (sys.path import), and 1 more
Produces
excluded_publisher, climate_policy_priority, lane_label, topics_of, technology_of, category_of, Repd, newest_repd_csv, is_uk, label, priority_label, load_feeds
Defines here
excluded_publisher, _rx, climate_policy_priority, lane_label, topics_of, technology_of, category_of, Repd, __init__, load, match, _name_segments, _authority, _agreement, newest_repd_csv, is_uk, label, priority_label
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/pipeline_headlines.py:1-462 · blob f49b65bc28657fdb414c03e577f9b8a3b6002d01 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Pipeline headlines: fresh UK renewables, storage, grid and data-centre headlines for Pipeline News.

Reads the public RSS/Atom feeds listed in automation/news/pipeline_feeds.json and writes
dist/pipeline_headlines.json (schema automation/news/schema/pipeline-headlines.v1.schema.json).

  python3 automation/news/pipeline_headlines.py --out dist/pipeline_headlines.json
  python3 automation/news/pipeline_headlines.py --probe report.md      # feed health report, writes no data file

The rule, in one sentence: keep a headline when its TITLE names a topic (solar, wind, storage, grid, data centre,
renewables) AND carries an event word (refused, approved, consent, DCO, financial close, construction, energised,
appeal, ...), and the story is about the UK.

- Source order (owner, 14 Nov 2026): BBC News first, Solar Power Portal second, then the rest. Feeds are
  fetched in the order of the list.
- Lane "keywords" (BBC News; "The main priority news feed is with key words solar and data centres and from
  BBC news rss feed"): a BBC item whose title or feed summary says solar or data centre is kept even with no
  event word, because BBC titles rarely name the project ("huge solar farm on palace estate"). It gets the
  event category when the title has an event word, otherwise "other" (solar) or "datacentre".
- Two narrow world-news lanes, each capped at the newest 10 so UK planning news is never crowded out:
  "datacentre_money" (Bloomberg and data-centre titles: data centres or AI infrastructure AND money or
  markets; category datacentre) and "china_solar" (pv magazine: China or a Chinese manufacturer AND solar,
  modules, polysilicon, prices, exports or tariffs; category other, technology solar). These are not UK news
  and nothing marks them as UK; they never get a REPD match.
- Headlines and links only. Only title, link, source and date are stored. The feed summary is read in memory
  for the BBC keywords lane alone and is never written out; no article page is requested.
- On a feed that is not UK-only the title must itself say it is UK news: a UK word, a REPD county, or a REPD
  site name. A title that names another country and no UK word is dropped on every feed.
- One category per headline from a fixed list; technology when the title says it.
- possible_match: only when the title contains a whole name segment of a REPD Site Name (word-bounded, at
  least two words or a distinctive single word) AND a second thing in the title agrees with that REPD row:
  the developer, the planning authority, the county or the technology (a single-word name needs one of the
  first three; technology alone is not enough for it). Exactly one REPD site must remain
  (co-located rows sharing one Site Name and county count as one site; the lowest Ref ID is given); otherwise null. It is a labelled possible match for review, never a confirmed link.
- Fetching, feed parsing, dates, canonical links, the sponsored filter and the link merge are imported from
  datacentre_feed.py; nothing is copied. One feed failing is recorded in "feeds" and never stops the run.
"""
from __future__ import annotations

import argparse
import csv
import datetime as dt
import io
import json
import re
import sys
from pathlib import Path
from urllib.parse import urlsplit

HERE = Path(__file__).resolve().parent
if str(HERE) not in sys.path:
    sys.path.insert(0, str(HERE))

import datacentre_feed as D  # noqa: E402  fetch, parse, dates, links, sponsored filter, merge
import names as N  # noqa: E402  the shared REPD name normalisation
import research_indexes as R  # noqa: E402  bounded HTML index source discovery

SCHEMA = "globalgrid2050.news.pipeline-headlines.v1"
MAX_ITEMS = 200
MAX_AGE_DAYS = 120
CATEGORIES = ("planning_decision", "consent", "refusal", "dco", "finance", "construction", "energisation",
              "grid", "policy", "datacentre", "other")
TECHNOLOGIES = ("solar", "wind", "offshore_wind", "battery", "hydro", "tidal")
ITEM_FIELDS = ("title", "link", "source", "date", "first_seen", "category", "technology", "possible_match")
SCOPE = ("Headlines and links from public RSS/Atom, English-language institutional indexes and explicitly curated "
         "primary-source leads; no article text is stored. Category and technology "
         "are labels read from the headline. A possible match is a name coincidence for review, not a confirmed "
         "link to a REPD project. COP31 and substantive global climate-policy headlines are world policy news "
         "with no REPD identity inference. Data-centre, China solar and institutional research headlines are world news.")
WORLD_LANES = ("datacentre_money", "china_solar", "global_context")
LANE_CAP = 10
WORLD_LANE_CAPS = {"datacentre_money": 10, "china_solar": 10, "global_context": 35}

# Owner-excluded publisher, enforced on fresh feeds AND retained historic headlines.
# Never request or display Solar Power Portal, including syndication links.
EXCLUDED_PUBLISHERS = frozenset({"solar power portal"})
EXCLUDED_DOMAIN = "solarpowerportal.co.uk"


def excluded_publisher(source, link=""):
    if str(source or "").strip().casefold() in EXCLUDED_PUBLISHERS:
        return True
    try:
        host = (urlsplit(str(link or "")).hostname or "").casefold().rstrip(".")
    except ValueError:
        return False
    return host == EXCLUDED_DOMAIN or host.endswith("." + EXCLUDED_DOMAIN)


def _rx(pattern):
    return re.compile(r"(?<![\w])(?:" + pattern + r")(?![\w])", re.I)


# ---------------------------------------------------------------- topic (title only)

TOPICS = {
    "solar": _rx(r"solar(?!\s+(?:eclipse|system|storm|flare|wind|orbiter))|photovoltaics?|PV"),
    "wind": _rx(r"wind[\s-]?farms?|wind[\s-]?turbines?|turbines?|offshore wind|onshore wind|floating wind|"
                r"wind (?:power|energy|projects?|parks?|capacity|developers?|sector|industry)"),
    "storage": _rx(r"batter(?:y|ies)(?: energy)? storage|BESS|energy storage|battery (?:sites?|farms?|parks?|"
                   r"projects?|facilit(?:y|ies)|schemes?|units?)|pumped (?:hydro|storage)|"
                   r"(?<!EV )(?<!car )(?<!vehicle )(?<!phone )batter(?:y|ies)(?! (?:factor|plant|gigafactor|recycl|fire|maker|cell|swap))"),
    "grid": _rx(r"national grid|NESO|Ofgem|grid connections?|connections? queue|electricity (?:grid|networks?|"
                r"transmission|superhighway)|power grid|grid (?:upgrades?|reforms?|capacity|queue|operator|"
                r"infrastructure|reinforcement)|pylons?|substations?|interconnectors?|transmission (?:lines?|"
                r"networks?|upgrades?|infrastructure|assets)|overhead lines?|power lines?|(?:power|subsea|undersea) cables?"),
    "renewables": _rx(r"renewables?|clean energy|clean power|green energy|energy parks?|tidal (?:energy|power|"
                      r"stream|lagoon|park|project|array)|hydro(?:electric)? (?:scheme|project|plant|power)"),
    "datacentre": _rx(r"data[\s-]?cent(?:re|er)s?|hyperscal(?:e|er|ers)|AI growth zones?"),
}
ENERGY_TOPICS = ("solar", "wind", "storage", "grid", "renewables")

# Global climate diplomacy is a bounded policy lane, not REPD project evidence.
# COP31 gets first research priority; other COP coverage needs a concrete
# international energy/climate-policy cue. Generic weather/climate is excluded.
COP31 = _rx(r"COP[\s-]?31")
COP_SUMMIT = _rx(r"COP[\s-]?\d{2}|UN climate (?:summit|talks|conference)")
CLIMATE_POLICY_CUE = _rx(r"climate|fossil[\s-]?fuels?|coal|oil|gas|emissions?|net[\s-]?zero|"
                         r"global warming|carbon|agreement|deal|treaty|negotiat(?:e|ion|ions|ing)|"
                         r"phase[\s-]?out|transition|adaptation|finance|funding|summit|talks")
CLIMATE_POLICY_EVENT = _rx(r"deal|negotiat(?:e|ion|ions|ing)|agreement|deadlock|talks|"
                           r"draft|reject|phase[\s-]?out|funding|finance|pledge|"
                           r"fossil[\s-]?fuels?|emissions?|coal|oil|gas|policy|commitment|summit")


def climate_policy_priority(title):
    """2: COP31 policy, 1: other substantive UN COP climate-policy news, else 0.

    This title-only, publisher-neutral rule cannot create a REPD association.
    """
    if not title or EXCLUDE.search(title):
        return 0
    if COP31.search(title) and CLIMATE_POLICY_CUE.search(title):
        return 2
    if COP_SUMMIT.search(title) and CLIMATE_POLICY_CUE.search(title) and CLIMATE_POLICY_EVENT.search(title):
        return 1
    return 0

# ---------------------------------------------------------------- event words (title only)

LEGAL = _rx(r"judicial review|high court|court of (?:appeal|session)|supreme court|challeng(?:e|es|ed)|lawful|"
            r"unlawful|court|judge|quash(?:ed|es)?")
REFUSAL = _rx(r"refus(?:e|es|ed|al|als|ing)|reject(?:s|ed|ion|ing)?|turn(?:s|ed)? down|thrown out|throws? out|"
              r"block(?:s|ed)|denied|dismiss(?:ed|es)|says? no|appeal fail(?:s|ed)|"
              r"(?:loses?|lost) (?:\w+ )?appeal")
CONSENT = _rx(r"approv(?:e|es|ed|al|als)|grant(?:s|ed)|consents|consented|go[\s-]ahead|green[\s-]?lit|"
              r"green[\s-]light(?:s|ed)?|given the nod|gets? the nod|allowed|"
              r"(?:wins?|won|secur(?:e|es|ed)|gets?|gains?|gained|receiv(?:e|es|ed)|awarded|obtain(?:s|ed)?|lands?)"
              r"\b.{0,50}\b(?:consents?|permission|approval|DCOs?)|"
              r"(?:consent|permission) (?:given|secured|awarded|won)|(?:wins?|won) (?:\w+ )?appeal|"
              r"appeal (?:allowed|upheld|succeeds|success|win|victory)")
CANCELLED = _rx(r"cancel(?:s|led|lation)?|scrap(?:s|ped)?|shelv(?:e|es|ed)|withdr(?:aw|aws|awn|ew)|abandon(?:s|ed)?|"
                r"axe[sd]?|pull(?:s|ed) (?:out|the plug)|halt(?:s|ed)?|paus(?:e|es|ed)")
ENERGISED = _rx(r"energi[sz](?:e|es|ed|ation)|switch(?:es|ed)? on|go(?:es)? live|went live|operational|"
                r"commission(?:s|ed|ing)|comes? online|came online|first power|starts? (?:generating|exporting|"
                r"operations?)|begins? (?:generating|exporting|operations?)|connect(?:s|ed) to (?:the )?(?:national )?grid|"
                r"fully (?:operational|online)|officially open(?:s|ed)?|(?:enters?|into|begins?|starts?) (?:commercial )?"
                r"operations?|commercial operations?")
CONSTRUCTION = _rx(r"construction|break(?:s|ing)? ground|broke ground|ground[\s-]?breaking|"
                   r"(?:work|works|building|build) (?:start|starts|started|begin|begins|began|under ?way|to start|to begin)|"
                   r"start(?:s|ed)? (?:works?|building)|begins? (?:works?|building)|install(?:s|ed|ation|ing)|"
                   r"milestone|contractor|EPC|kicks? off")
FINANCE = _rx(r"financial close|financ(?:e|es|ed|ing)|refinanc(?:e|es|ed|ing)|fund(?:s|ed|ing)|invest(?:s|ed|ing|"
              r"ment|ments|or|ors)?|acqui(?:re|res|red|sition)|buys?|bought|sells?|sold|sale|stake|loans?|"
              r"debt|raises?|raised|joint venture|joins? forces|CfDs?|contracts? for difference|auction|AR[78]|tolling|PPA|offtake")
DCO = _rx(r"DCOs?|development consent|nationally significant|NSIPs?|examination|planning inspectorate|section 36|"
          r"recommendation")
DECISION = _rx(r"decisions?|decid(?:e|es|ed)|ruling|rules|ruled|appeals?|inquiry|verdict|call(?:ed|s)?[\s-]in|"
               r"planning (?:committee|permission)|secretary of state|ministers?|clear(?:s|ed)")
GRID_EVENT = _rx(r"connections?|connect(?:s|ed)|upgrad(?:e|es|ed)|reinforcement|queue|reforms?|capacity|"
                 r"constraints?|route|corridor|offers?")
POLICY = _rx(r"polic(?:y|ies)|consultations?|government|bills?|strateg(?:y|ies)|reforms?|rules|regulations?|"
             r"targets?|DESNZ|Miliband|parliament|MPs?|plan to|taskforce")
WEAK = _rx(r"planning|plans? (?:submitted|lodged|unveiled|revealed)|submit(?:s|ted)|lodg(?:es|ed)|applications?|"
           r"proposals?|consent")
POLICY_BODY = _rx(r"Ofgem|NESO|reforms?|polic(?:y|ies)|strateg(?:y|ies)|bills?|consultations?|rules|regulations?")
PROJECT_NOUN = _rx(r"farms?|parks?|projects?|plants?|sites?|schemes?|arrays?|stations?|substations?|"
                   r"interconnectors?|cables?|pylons?|lines?|BESS|windfarms?|turbines?|DCOs?")
DC_EXTRA = _rx(r"planning|council|ministers?|government|grid|power|energy|water|billions?|millions?|"
               r"\d[\d.,]*\s?(?:bn|m)|campus|build(?:s|ing)?|expan(?:d|ds|ded|sion)|capex|spend(?:s|ing)?")

TECH_RULES = (
    ("offshore_wind", _rx(r"offshore wind|floating wind|offshore wind[\s-]?farms?")),
    ("solar", TOPICS["solar"]),
    ("wind", _rx(r"wind|windfarms?|turbines?")),
    ("battery", _rx(r"batter(?:y|ies)|BESS|energy storage")),
    ("hydro", _rx(r"pumped (?:hydro|storage)|hydro(?:electric)?")),
    ("tidal", _rx(r"tidal")),
)

UK_WORDS = _rx(r"UK|U\.K\.|Britain|British|Great Britain|GB|England|English|Scotland|Scottish|Scots|"
               r"(?<!New South )Wales|Welsh|"
               r"Northern Ireland|Ofgem|NESO|National Grid|DESNZ|Miliband|Crown Estate|Planning Inspectorate|"
               r"Celtic Sea|Irish Sea|North Sea|Dogger Bank|Hornsea|East Anglia|Moray|Shetland|Orkney|Humber|London")
# A headline that names another country and no UK word is not UK news, whatever feed carried it.
FOREIGN = _rx(r"US|U\.S\.|USA|America|American|EU|Europe-wide|Ireland|Irish|Germany|German|France|French|Spain|"
              r"Spanish|Italy|Greece|Netherlands|Dutch|Poland|China|Chinese|India|Japan|Australia|Australian|"
              r"Canada|Texas|California|Singapore|Brazil|Africa|Taiwan|Korean?|Finland|Finnish|Norway|Norwegian|"
              r"Denmark|Danish|Sweden|Swedish|Belgium|Belgian|Baltic|New South Wales|Queensland|Vietnam|Philippines")
# Not this page's subject even when a topic word is present.
EXCLUDE = _rx(r"gas fields?|oil ?fields?|speech|solar (?:eclipse|system|storm|flare)|need to know")

# World lanes (title only).
AI_INFRA = _rx(r"data[\s-]?cent(?:re|er)s?|hyperscal(?:e|er|ers)|AI (?:infrastructure|capex|spending|boom|bubble|"
               r"build[\s-]?out|investments?|chips?|compute|trade|stocks?|rally|debt|bonds?)|compute capacity")
MONEY = _rx(r"capex|capital expenditure|spend(?:s|ing)?|invest(?:s|ed|ing|ment|ments|or|ors)?|bonds?|debt|loans?|"
            r"valuations?|valued|bubble|shares?|stocks?|earnings|revenue|profits?|fund(?:s|ed|ing)?|financ(?:e|es|ed|ing)|"
            r"raises?|raised|IPO|markets?|rally|sell[\s-]?off|euphoria|boom|billions?|millions?|trillions?|"
            r"[$£€]\s?\d[\d.,]*\s?(?:bn|m|tn|billion|million|trillion)?(?:-plus)?")
CHINA = _rx(r"China|Chinese|LONGi|Jinko(?:Solar)?|Trina(?: Solar)?|JA Solar|Tongwei|GCL(?: Tech)?|Daqo|Risen|"
            r"Astronergy|DAS Solar|Aiko|Huasun|Sungrow|TCL Zhonghuan|Canadian Solar")
SOLAR_TRADE = _rx(r"solar|PV|photovoltaics?|modules?|polysilicon|wafers?|cells?|prices?|exports?|tariffs?")


RESEARCH_GRID = _rx(r"electricity (?:grid|networks?|demand|supply)|power (?:grid|supply|demand|system|infrastructure)|"
                    r"grid (?:capacity|constraints?|connections?|bottlenecks?|reinforcement|investment)|"
                    r"transmission (?:grids?|networks?|capacity)|energy transition|renewable energy|"
                    r"electricity infrastructure|energy infrastructure")
RESEARCH_MACRO = _rx(r"interest rates?|bank rate|federal funds|monetary policy|inflation|"
                     r"bond yields?|gilt yields?|borrowing costs?|credit conditions?|financial stability|"
                     r"capital markets?|infrastructure (?:financing|investment)|project finance|"
                     r"cost of capital")
RESEARCH_ENERGY = _rx(r"solar|wind (?:power|energy|capacity)|batter(?:y|ies) (?:storage|energy)|BESS|"
                      r"renewables?|power (?:generation|markets?|prices?)|electricity|energy transition")


def lane_label(title, lane, focus=None):
    """World context is attributed discovery, never a REPD fact or implied UK event."""
    if lane == "datacentre_money":
        return ("datacentre", None, None) if AI_INFRA.search(title) and MONEY.search(title) else None
    if lane == "china_solar":
        return ("other", "solar", None) if CHINA.search(title) and SOLAR_TRADE.search(title) else None
    if lane == "global_context":
        if EXCLUDE.search(title) or BRANDED.search(title) or D.SPONSORED_RE.search(title):
            return None
        if TOPICS["datacentre"].search(title):
            return ("datacentre", None, None)
        if TOPICS["grid"].search(title) or RESEARCH_GRID.search(title):
            return ("grid", None, None)
        if RESEARCH_ENERGY.search(title):
            return ("policy" if POLICY.search(title) else "other", technology_of(title), None)
        if RESEARCH_MACRO.search(title) and focus != "energy_research":
            return ("finance", None, None)
    return None

# Paid-for items the shared sponsored filter does not name.
BRANDED = _rx(r"branded content|sponsored feature|promotional feature")
# Opinion columns and letters are not project news (The Guardian marks them with " | Author").
OPINION_HOSTS = ("www.theguardian.com",)


def topics_of(title):
    return [name for name, rx in TOPICS.items() if rx.search(title)]


def technology_of(title):
    for tech, rx in TECH_RULES:
        if rx.search(title):
            return tech
    return None


def category_of(title, topics=None):
    """One category from CATEGORIES for an in-scope title, or None when it carries no event word.
    topics: given by the priority lane when the topic was found in the feed summary, not the title."""
    topics = topics or topics_of(title)
    if EXCLUDE.search(title):
        return None
    if climate_policy_priority(title):
        return "policy"
    if not topics:
        return None
    if topics == ["datacentre"]:
        if any(rx.search(title) for rx in (REFUSAL, CONSENT, FINANCE, CONSTRUCTION, DECISION, POLICY, DC_EXTRA, WEAK)):
            return "datacentre"
        return None
    has = lambda rx: bool(rx.search(title))  # noqa: E731
    # A regulator or policy headline with no project noun ("Ofgem approves connection reform") is not a consent.
    if has(POLICY_BODY) and not has(PROJECT_NOUN):
        if not any(has(rx) for rx in (REFUSAL, CONSENT, FINANCE, DECISION, GRID_EVENT, POLICY, WEAK)):
            return None
        return "grid" if "grid" in topics else "policy"
    if has(LEGAL):
        return "planning_decision"          # outcome of a court case is not safely read from a headline
    if has(REFUSAL):
        return "refusal"
    if has(CONSENT):
        return "consent"
    if has(CANCELLED):
        return "other"
    if has(ENERGISED):
        return "energisation"
    if has(CONSTRUCTION):
        return "construction"
    if has(FINANCE):
        return "finance"
    if has(DCO):
        return "dco"
    if has(DECISION):
        return "planning_decision"
    if "grid" in topics and has(GRID_EVENT):
        return "grid"
    if has(POLICY):
        return "policy"
    if has(WEAK):
        return "other"
    return None


# ---------------------------------------------------------------- REPD possible match

# Words that do not make a REPD name segment distinctive ("Data Centre", "Clean Energy").
_GENERIC = frozenset({"data", "clean", "smart", "city", "town", "county", "national", "central",
                      "community", "village", "garden", "retail", "science", "technology", "distribution"})


class Repd:
    """Name segments of REPD Site Names, for the possible-match rule. Empty when no CSV is given."""

    def __init__(self, rows=()):
        self.by_phrase = {}
        self.counties = set()
        place_tokens = set()
        rows = list(rows)
        for r in rows:
            for field in ("County", "Planning Authority", "Region"):
                place_tokens.update(N.norm(r.get(field)).split())
            county = N.norm(r.get("County"))
            if len(county) >= 4 and county not in ("offshore", "central", "islands", "borders", "jersey", "tock"):
                self.counties.add(county)
        for r in rows:
            ref, site = N.clean(r.get("Ref ID")), N.clean(r.get("Site Name"))
            if not ref or not site:
                continue
            parts = N.segments(site)
            for seg in _name_segments(parts):
                phrase = N.norm(seg)
                toks = phrase.split()
                distinct = [t for t in toks if len(t) >= 4 and not t.isdigit() and t not in N.NAME_BOILERPLATE
                            and t not in N.GENERIC_SINGLE and t not in N.ADDRESS_ONLY and t not in _GENERIC]
                if not distinct:
                    continue
                if len(toks) == 1 and (len(toks[0]) < 7 or toks[0] in place_tokens):
                    continue        # a single word must be distinctive: long, and not a county or authority word
                self.by_phrase.setdefault(phrase, {})[ref] = {
                    "ref": ref, "site_name": site, "family": N.tech_family(r.get("Technology Type")),
                    "operator": N.operator_tokens(r.get("Operator (or Applicant)")),
                    "authority": _authority(r.get("Planning Authority")), "county": N.norm(r.get("County"))}
        self.max_words = max((len(p.split()) for p in self.by_phrase), default=0)

    @classmethod
    def load(cls, path):
        if not path or not Path(path).exists():
            return cls()
        raw = Path(path).read_bytes()
        try:
            text = raw.decode("utf-8-sig")
        except UnicodeDecodeError:
            text = raw.decode("cp1252")
        return cls(csv.DictReader(io.StringIO(text)))

    def match(self, title):
        """{"repd_ref", "site_name", "basis"} or None. Longest name first; exactly one REPD site must remain."""
        text = N.padded(title)
        toks = text.split()
        for size in range(min(self.max_words, len(toks)), 0, -1):
            found = None
            for i in range(len(toks) - size + 1):
                phrase = " ".join(toks[i:i + size])
                rows = self.by_phrase.get(phrase)
                if not rows:
                    continue
                if size == 1 and not N.descriptor_adjacent(text, phrase):
                    continue        # a single word counts only right before a technology word ("Xyzzy solar")
                rest = N.padded(" ".join(toks[:i] + toks[i + size:]))
                agreed = {}
                for ref, row in rows.items():
                    # one word plus a technology word is too weak ("Hunterston battery" fits more than one
                    # project): a single-word name needs the developer, the planning authority or the county
                    basis = _agreement(row, rest, N.tech_context(text) if size > 1 else ())
                    if basis:
                        agreed[ref] = (row, basis)
                named = {ref: v for ref, v in agreed.items() if v[1] != "technology"}
                agreed = named or agreed    # a developer, authority or county in the headline outranks technology
                if agreed and len({(row["site_name"], row["county"]) for row, _ in agreed.values()}) == 1:
                    # one row, or co-located rows of one site (same Site Name and county): lowest Ref ID stands for it
                    row, basis = agreed[min(agreed, key=lambda r: (len(r), r))]
                    found = {"repd_ref": row["ref"], "site_name": row["site_name"], "basis": basis}
                    break
                if agreed:
                    return None     # the name fits more than one REPD row: say nothing
            if found:
                return found
        return None


_COLOCATED_TAIL = re.compile(r"\s+(?:&|and)\s+(.+)$", re.I)


def _name_segments(parts):
    """First and last segment of a REPD Site Name as written, and each of them without a trailing
    '& Battery Storage'-style tail (a tail made only of technology words describes the co-located plant)."""
    out = []
    for seg in ([parts[0], parts[-1]] if parts else []):
        out.append(seg)
        tail = _COLOCATED_TAIL.search(seg)
        if tail and all(t in N.NAME_BOILERPLATE for t in N.norm(tail.group(1)).split()):
            out.append(seg[:tail.start()])
    return list(dict.fromkeys(out))


def _authority(value):
    parts = N.segments(value)
    toks = [t for t in N.norm(parts[0] if parts else "").split() if t not in ("the", "council")]
    return " ".join(toks)


def _agreement(row, rest, families):
    """What else in the headline agrees with this REPD row. rest = the headline without the matched name."""
    if row["operator"] & set(rest.split()):
        return "developer"
    if len(row["authority"]) >= 5 and N.contains_phrase(rest, row["authority"]):
        return "planning_authority"
    if len(row["county"]) >= 5 and row["county"] != "offshore" and N.contains_phrase(rest, row["county"]):
        return "county"
    if row["family"] in families:
        return "technology"
    return None


def newest_repd_csv(root):
    """The newest quarterly REPD file in the repository root (repd-2026q3.csv, ...), or None."""
    found = sorted(Path(root).glob("repd-20[0-9][0-9]q[1-4].csv"))
    return str(found[-1]) if found else None


# ---------------------------------------------------------------- collect, dedupe, build

def is_uk(title, repd):
    """The title itself says this is UK news: a UK word, a REPD county, or a REPD site name of two words or more."""
    if UK_WORDS.search(title):
        return True
    padded = N.padded(title)
    if any(N.contains_phrase(padded, county) for county in repd.counties):
        return True
    toks = padded.split()
    return any(" ".join(toks[i:i + size]) in repd.by_phrase
               for size in range(2, min(repd.max_words, len(toks)) + 1) for i in range(len(toks) - size + 1))


def label(title, repd):
    """(category, technology, possible_match) for a kept title, or None when the title is out of scope."""
    if climate_policy_priority(title):
        return "policy", None, None  # World policy cannot identify an REPD project.
    category = category_of(title)
    if category is None:
        return None
    match = None if category == "datacentre" else repd.match(title)
    return category, technology_of(title), match


def priority_label(title, summary, repd):