GLOBALGRID2050 / EXPLORE CODE

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

Official and 1 more file

A Python command-line tool in the signals folder of GlobalGrid2050 that fetches search, top200 solar, aliases and the Renewable Energy Planning Database (REPD) register.

700 lines of Python from globalgrid2050, in 2 files. Topic: Electricity markets and data pipelines. Section 794 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 — Signals storage · globalgrid2050 / automation/news/signals/index.py lines 701–932
  2. Official storage · globalgrid2050 / automation/news/signals/official.py lines 1–468

News — Signals

A Python command-line tool in the automation folder of GlobalGrid2050 that fetches project signals, top200 solar, aliases and ground truth.

storageglobalgrid2050 / automation/news/signals/index.py · lines 701–932 of 932 (continued from section 793) · Entry point · pattern _under (shared by 2 files)

What it does
It fetches project signals, top200 solar, aliases and ground truth. Defines 40 functions or classes, including scrub, clean_site_name, core_name, phrase_rx, load_projects. Uses libraries __future__, argparse, datetime, json, re. 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.
Inputs & outputs
In: JSON file project_signals_index.json; JSON file top200_solar.json; JSON file aliases.json; JSON file index_ground_truth.json; command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It cleans site name (`clean_site_name`), loads projects (`load_projects`) and fetches feed (`fetch_feed`). Project signals, part "index": BBC News RSS, the Guardian's RSS by tag and the GDELT DOC 2.0 API. It accepts `--out`, `--top200` and `--aliases`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · automation/news/signals · Python CLI
Uses
Dates (import), Gate (import), Combine (import), __future__, argparse, datetime, json, re, sys, time, urllib.error
Used by
none found
Produces
scrub, clean_site_name, core_name, phrase_rx, load_projects, match_item, domain_of, is_excluded, publisher_of, make_item, bbc_feeds, Throttle
Defines here
tidy, coverage, probe_report, main
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/signals/index.py:701-932 · blob 50575f3424bfc70aef5189c7735dc4815ce12ce9 · 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
                         gdelt_url(gdelt_query(phrase, "uk").replace(" sourcecountry:UK", ""), GDELT_WINDOWS[0][1], client.now)))
        for label, url in variants:
            status, text = client._get(url)
            if status != 200:
                row[label] = "HTTP %s" % status
                if status == 429:
                    client.sleep(10)
                continue
            try:
                arts = parse_gdelt(text)
                dates = sorted(a[3] for a in arts if a[3])
                row[label] = "%d articles%s" % (len(arts), (", %s to %s" % (dates[0], dates[-1])) if dates else "")
            except ValueError as error:
                row[label] = "message: " + str(error)[:90]
        rows.append(row)
    return rows


# ---------------------------------------------------------------- assemble

FAMILY_ORDER = {"official": 0, "bbc": 1, "trade": 2, "national": 3, "regional": 4}


def tidy(items, previous_items=(), valid_refs=None, cap=MAX_PER_PROJECT):
    """Dedupe by (project, link); a confirmed item beats an uncertain one; newest first; cap per project."""
    best = {}
    for item in list(items) + [i for i in previous_items if isinstance(i, dict)]:
        if valid_refs is not None and item.get("repd_ref") not in valid_refs:
            continue
        if not item.get("link") or not item.get("title") or is_excluded(item["link"]):
            continue
        key = (item["repd_ref"], item["link"])
        held = best.get(key)
        if held is None or (held["confidence"] != "confirmed" and item.get("confidence") == "confirmed"):
            best[key] = item
    by_project = {}
    for item in best.values():
        by_project.setdefault(item["repd_ref"], []).append(item)
    out = []
    for ref in sorted(by_project, key=lambda r: (len(r), r)):
        rows = sorted(by_project[ref], key=lambda i: (i["confidence"] != "confirmed", -int((i["date"] or "0000-00-00").replace("-", "")),
                                                      FAMILY_ORDER.get(i["family"], 9), i["link"]))
        seen, unique = set(), []
        for row in rows:                                   # one syndicated story, many local titles: keep one
            key = re.sub(r"[^a-z0-9]+", " ", row["title"].lower()).strip()
            if key not in seen:
                seen.add(key)
                unique.append(row)
        out.extend(unique[:cap])
    return out


def coverage(items, projects):
    refs = {p["repd_ref"] for p in projects}
    any_ref = {i["repd_ref"] for i in items} & refs
    confirmed = {i["repd_ref"] for i in items if i["confidence"] == "confirmed"} & refs
    by_family = {}
    for family in FAMILY_ORDER:
        by_family[family] = len({i["repd_ref"] for i in items if i["family"] == family} & refs)
    return {"projects": len(projects), "with_signal": len(any_ref), "with_confirmed_signal": len(confirmed),
            "with_signal_by_family": by_family, "items": len(items)}


def probe_report(part, projects, extra):
    cov, lines = part["coverage"], []
    lines.append("## Project signals, part \"index\" (BBC RSS, Guardian RSS, GDELT)\n")
    lines.append("Generated %s. Projects with at least one signal from these sources: **%d of %d** "
                 "(%d with a confirmed signal). Items kept: %d.\n" % (part["generated_at"], cov["with_signal"],
                                                                       cov["projects"], cov["with_confirmed_signal"], cov["items"]))
    lines.append("By family: " + ", ".join("%s %d" % kv for kv in cov["with_signal_by_family"].items()) + ".\n")
    lines.append("| source | status | requests | failures | items | error |\n|---|---|---|---|---|---|")
    for s in part["sources"]:
        lines.append("| %s | %s | %s | %s | %s | %s |" % (s["id"], s["status"], s["requests"], s["failures"], s["items"],
                                                          s["error"].replace("|", "/")))
    g = part.get("gdelt") or {}
    if g:
        lines.append("\n### GDELT DOC 2.0: what it returned\n")
        lines.append("- requests %(requests)s, answered %(answered)s, cache hits %(cache_hits)s, HTTP 429 %(http_429)s, "
                     "queries refused twice %(refused_queries)s, errors %(errors)s, queries with no article %(empty)s, articles returned %(articles)s, "
                     "projects not asked this run %(not_asked)s" % g)
        lines.append("- window in use: %s%s" % (g.get("window") or "none answered", ("; stopped: " + g["stopped"]) if g.get("stopped") else ""))
        if g.get("error_samples"):
            lines.append("- messages from GDELT: " + " / ".join(g["error_samples"]))
        lines.append("- projects asked %s; with any article returned %s; with a kept item %s; with a headline that names "
                     "the project %s" % (g.get("projects_asked"), g.get("projects_with_articles"),
                                         g.get("projects_with_kept"), g.get("projects_with_strong")))
        lines.append("- dropped: " + ", ".join("%s %d" % kv for kv in (g.get("dropped") or {}).items()))
        dates = sorted(i["date"] for i in part["items"] if i["basis"].startswith("GDELT") and i["date"])
        if dates:
            lines.append("- dates of kept GDELT items: %s to %s" % (dates[0], dates[-1]))
        if g.get("domains"):
            lines.append("- domains of kept items: " + ", ".join("%s %d" % kv for kv in g["domains"]))
    if extra.get("experiment"):
        lines.append("\n### GDELT windows and scopes compared (same phrase, first projects)\n")
        keys = [k for k in extra["experiment"][0] if k not in ("repd_ref", "phrase")]
        lines.append("| REPD | phrase | " + " | ".join(keys) + " |\n|---|---|" + "---|" * len(keys))
        for row in extra["experiment"]:
            lines.append("| %s | %s | %s |" % (row["repd_ref"], row["phrase"], " | ".join(str(row.get(k, "")) for k in keys)))
    lines.append("\n### Feeds\n")
    if extra.get("unmapped_counties"):
        lines.append("Counties with no BBC regional feed in the table: %s\n" % ", ".join(extra["unmapped_counties"]))
    lines.append("| feed | status | entries | mention solar | kept | newest | error |\n|---|---|---|---|---|---|---|")
    for h in part.get("feeds", []):
        lines.append("| %s | %s | %s | %s | %s | %s | %s |" % (h["url"].replace("https://", ""), h["status"], h["entries"],
                                                               h["solar"], h["kept"], (h["newest"] or "")[:10],
                                                               h["error"].replace("|", "/")))
    lines.append("\n### Items (first 60)\n\n| REPD | date | family | publisher | confidence | title | basis |\n|---|---|---|---|---|---|---|")
    for i in part["items"][:60]:
        lines.append("| %s | %s | %s | %s | %s | [%s](%s) | %s |" % (
            i["repd_ref"], i["date"] or "", i["family"], i["publisher"], i["confidence"],
            i["title"].replace("|", "/").replace("[", "(").replace("]", ")"), i["link"], i["basis"].replace("|", "/")))
    if extra.get("unmatched"):
        lines.append("\n### Feed items that say solar and matched none of the 200 (headlines only)\n")
        for link, (publisher, date, title) in list(extra["unmatched"].items())[:50]:
            lines.append("- %s %s: [%s](%s)" % (date, publisher, title.replace("[", "(").replace("]", ")"), link))
    if extra.get("truth"):
        lines.append("\n" + extra["truth"])
    return "\n".join(lines) + "\n"


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--out", default="dist/project_signals_index.json")
    ap.add_argument("--top200", default=str(HERE / "top200_solar.json"))
    ap.add_argument("--aliases", default=str(HERE / "aliases.json"))
    ap.add_argument("--previous", default=None, help="an earlier part file; its items are kept (rolling feeds)")
    ap.add_argument("--cache", default=None, help="GDELT answers by query (JSON), read and rewritten")
    ap.add_argument("--probe", default=None, help="write a Markdown report here as well")
    ap.add_argument("--truth", default=str(HERE / "index_ground_truth.json"), help="ground truth for the probe report")
    ap.add_argument("--limit", type=int, default=None, help="only the first N projects by rank")
    ap.add_argument("--gdelt-max", type=int, default=GDELT_DEFAULT_CAP, help="GDELT requests this run (0 = skip)")
    ap.add_argument("--gdelt-seconds", type=int, default=1200, help="time budget for GDELT this run")
    ap.add_argument("--gdelt-scope", choices=("uk", "domains"), default="uk")
    ap.add_argument("--gdelt-experiment", type=int, default=0, help="compare windows and scopes for the first N")
    ap.add_argument("--skip-rss", action="store_true")
    ap.add_argument("--now", default=None)
    args = ap.parse_args(argv)

    now_iso = args.now or dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
    projects = load_projects(args.top200, args.aliases)
    if args.limit:
        projects = projects[:args.limit]
    items, sources, feeds, extra = [], [], [], {}
    throttle = Throttle(1.0)

    if not args.skip_rss:
        collect_rss.unmatched.clear()
        extra["unmatched"] = collect_rss.unmatched
        bbc, extra["unmapped_counties"] = bbc_feeds(projects)
        found, health = collect_rss(bbc, projects, fetch_feed, "BBC News", "bbc", "BBC News RSS", throttle)
        items += found
        feeds += health
        sources.append(source_record("bbc-rss", BBC_BASE, health))
        found, health = collect_rss([(u, set()) for u in GUARDIAN_FEEDS], projects, fetch_feed, "The Guardian",
                                    "national", "Guardian RSS", throttle)
        items += found
        feeds += health
        sources.append(source_record("guardian-rss", "https://www.theguardian.com/", health))

    gdelt = {}
    if args.gdelt_max > 0:
        cache = {}
        if args.cache and Path(args.cache).exists():
            try:
                cache = json.loads(Path(args.cache).read_text(encoding="utf-8")).get("queries", {})
            except (ValueError, AttributeError):
                cache = {}
        client = Gdelt(fetch_gdelt, cache, now_iso, cap=args.gdelt_max, scope=args.gdelt_scope, seconds=args.gdelt_seconds)
        if args.gdelt_experiment:
            try:
                extra["experiment"] = gdelt_experiment(projects, client, args.gdelt_experiment)
            except Exception:  # an experiment only
                pass
        try:
            found, per_project, dropped = collect_gdelt(projects, client)
        except Exception as error:  # GDELT failing as a whole never stops the run
            found, per_project, dropped = [], {}, {}
            client.stats["stopped"] = (type(error).__name__ + ": " + str(error))[:160]
        items += found
        domains = {}
        for item in found:
            domains[domain_of(item["link"])] = domains.get(domain_of(item["link"]), 0) + 1
        gdelt = dict(client.stats, dropped=dropped, projects_asked=len(per_project),
                     projects_with_articles=sum(1 for v in per_project.values() if v["returned"]),
                     projects_with_kept=sum(1 for v in per_project.values() if v["kept"]),
                     projects_with_strong=sum(1 for v in per_project.values() if v["strong"]),
                     domains=sorted(domains.items(), key=lambda kv: (-kv[1], kv[0]))[:25], per_project=per_project)
        if args.cache:
            keep = {q: e for q, e in cache.items() if not e.get("error")}
            Path(args.cache).parent.mkdir(parents=True, exist_ok=True)
            Path(args.cache).write_text(json.dumps({"schema": "project-signals-gdelt-cache.v1", "queries": keep},
                                                   ensure_ascii=False) + "\n", encoding="utf-8")
        s = client.stats
        asked = s["requests"]
        status = "ok" if s["answered"] and not s["stopped"] and not s["errors"] else ("partial" if s["answered"] or s["cache_hits"] else "failed")
        sources.append({"id": "gdelt-doc", "url": GDELT_URL, "status": status, "requests": asked,
                        "failures": s["errors"] + s["http_429"], "items": len(found),
                        "error": scrub("; ".join(filter(None, [s["stopped"]] + s["error_samples"])))[:300]})

    previous_items = []
    if args.previous and Path(args.previous).exists():
        try:
            old = json.loads(Path(args.previous).read_text(encoding="utf-8"))
            if old.get("schema") == SCHEMA and old.get("team") == TEAM:
                previous_items = old.get("items") or []
        except (ValueError, AttributeError):
            previous_items = []
    items = tidy(items, previous_items, {p["repd_ref"] for p in projects})
    part = {"schema": SCHEMA, "team": TEAM, "generated_at": now_iso, "items": items, "sources": sources,
            "coverage": coverage(items, projects), "feeds": feeds, "gdelt": gdelt}
    out = Path(args.out)
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(json.dumps(part, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
    if args.probe:
        if args.truth and Path(args.truth).exists():
            try:
                import combine as C
                truth = C.load_truth(args.truth)
                by_ref = {}
                for item in items:
                    by_ref.setdefault(item["repd_ref"], []).append(item)
                extra["truth"] = C.truth_report(truth, by_ref, "this part alone")
            except Exception as error:  # the comparison is a report, never a reason to fail
                extra["truth"] = "Ground truth comparison unavailable: %s" % type(error).__name__
        report = probe_report(part, projects, extra)
        Path(args.probe).write_text(report, encoding="utf-8")
    print(json.dumps({"out": str(out), **part["coverage"], "sources": {s["id"]: s["status"] for s in sources}}))
    return 1 if sources and all(s["status"] == "failed" for s in sources) and not items else 0


if __name__ == "__main__":
    sys.exit(main())

Official

A Python command-line tool in the signals folder of GlobalGrid2050 that fetches search, top200 solar, aliases and the Renewable Energy Planning Database (REPD) register.

storageglobalgrid2050 / automation/news/signals/official.py · lines 1–468 of 730 · Entry point · pattern FetchError (shared by 2 files)

What it does
It fetches search, top200 solar, aliases and the REPD register. Defines 43 functions or classes, including now_utc, FetchError, __init__, _completed_context, _incomplete_chain. 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.
Inputs & outputs
In: JSON file search.json; JSON file top200_solar.json; JSON file aliases.json; command-line arguments.
Downstream impact
Used directly by 4 files: Planning File (globalgrid2050); Test Signals Official (globalgrid2050); Test Signals Planning File (globalgrid2050); GlobalGrid2050 Project Signals Official Workflow (globalgrid2050). Reached from 4 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); Combine (globalgrid2050).
What it achieves
It fetches error (`FetchError`), closes health (`close_health`) and loads projects (`load_projects`). Official-source signals for the 200 largest solar projects in the REPD (team "official"). It accepts `--out`, `--probe` and `--discover`.
Why it matters
Imported by Planning File. Run by GlobalGrid2050 Project Signals Official Workflow. Checked by 2 tests, including Test Signals Official.
Application
globalgrid2050 · automation/news/signals · Python CLI
Uses
Dates (import), Gate (import), Datacentre Feed (sys.path import), __future__, argparse, csv, datetime, io, json, re, sys
Used by
imported by Planning File (import), imported by Test Signals Official (sys.path import), imported by Test Signals Planning File (sys.path import), run by GlobalGrid2050 Project Signals Official Workflow (workflow run)
Produces
now_utc, FetchError, Fetcher, health, close_health, load_projects, derive_alias, phrase_in, alias_core, match, item, parse_day
Defines here
now_utc, FetchError, __init__, _completed_context, _incomplete_chain, _open, Fetcher, __init__, _wait, get, health, close_health, load_projects, derive_alias, _norm, phrase_in, alias_core, _facts, match, _match, item, parse_day, parse_pins_csv, col, _milestone, pins_lookup, pins_items, source_pins, govuk_url
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/signals/official.py:1-468 · blob 29495b1d70f6b60f52285246dcee5a4ad2806fa7 · 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
"""Official-source signals for the 200 largest solar projects in the REPD (team "official").

For each project in top200_solar.json, with the press alias from aliases.json, this asks sources that permit
automated access and keeps headlines, links and dates only (never page text):

  pins-register   the Planning Inspectorate's national infrastructure project list (one CSV download), matched on the
                  project reference (EN01xxxx) and, failing that, on the alias; gives the stage and milestone dates
  govuk-search    the GOV.UK search API (https://www.gov.uk/api/search.json): exact alias phrase, and the planning
                  reference where the project has a national one; decision pages for development consent, notices
  ecu-case        the Scottish Energy Consents Unit case page for an ECU reference (title and existence)

Output (see SIGNALS-CONTRACT.md, "project-signals-part.v1"): items {repd_ref, title, link, publisher, date, family
"official", basis, confidence} and one health record per source. One failing source never stops a run; the exit code
is non-zero only when every source failed.

Politeness: a descriptive User-Agent, at most one request a second per host, a per-run cap per host, one retry after
ten seconds on HTTP 429, 20 second timeouts.

  python automation/news/signals/official.py --out part-official.json [--probe summary.md] [--limit N]
  python automation/news/signals/official.py --discover summary.md      (prints what each source returns; CI aid)
"""
from __future__ import annotations

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

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

if str(HERE) not in sys.path:
    sys.path.insert(0, str(HERE))

import dates as DATES  # noqa: E402  one date rule shared by the collectors and the combiner
import gate as GATE  # noqa: E402  the title gate shared with trade.py, index.py and combine.py
import datacentre_feed as D  # noqa: E402  clean_text, canonical_link, parse_date

SCHEMA_PART = "project-signals-part.v1"
USER_AGENT = "GlobalGrid2050-ProjectSignals/1.0 (+https://globalgrid2050.com)"
TIMEOUT_S = 20
MAX_BYTES = 6_000_000
MIN_INTERVAL_S = 1.0
HOST_CAP = 450
TITLE_LIMIT = 300

PINS_HOST = "https://national-infrastructure-consenting.planninginspectorate.gov.uk"
PINS_CSV = PINS_HOST + "/api/applications-download"
PINS_PROJECT = PINS_HOST + "/projects/{ref}"
GOVUK_SEARCH = "https://www.gov.uk/api/search.json"
ECU_CASE = "https://www.energyconsents.scot/ApplicationDetails.aspx?cr={ref}"

PINS_REF_RE = re.compile(r"\bEN0\d{5,6}\b", re.I)
ECU_REF_RE = re.compile(r"\bECU\d{8}\b", re.I)
NATIONAL_REF_RE = re.compile(r"\b(?:EN0\d{5,6}|ECU\d{8}|DNS/\d{7}|CAS-\d{5}-[A-Z0-9]{6})\b", re.I)
TOPIC_RE = re.compile(r"\b(solar|photovoltaic|pv|energy|renewables?|battery|development consent)\b", re.I)
DISTINCTIVE_RE = re.compile(r"\b(solar|photovoltaic|pv|energy|renewables?)\b", re.I)


def now_utc():
    return dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")


# ---------------------------------------------------------------- fetching

class FetchError(Exception):
    def __init__(self, message, status=None):
        super().__init__(message)
        self.status = status


_CONTEXTS = {}      # host -> ssl context completed with the issuer certificate, or None when that failed


def _completed_context(host, opener=urllib.request.urlopen):
    """For a server that does not send its intermediate certificate (the Energy Consents Unit site): read the
    issuer's address from the server certificate (Authority Information Access), fetch that one certificate and
    add it to a normal verifying context. Verification is never switched off: the chain must still end at a
    trusted root, so a wrong or forged issuer certificate simply fails as before."""
    import os
    import ssl
    import tempfile
    pem = ssl.get_server_certificate((host, 443), timeout=TIMEOUT_S)        # read only, nothing trusted yet
    with tempfile.NamedTemporaryFile("w", suffix=".pem", delete=False) as handle:
        handle.write(pem)
    try:
        info = ssl._ssl._test_decode_cert(handle.name)                      # noqa: SLF001  the only stdlib decoder
    finally:
        os.unlink(handle.name)
    context = ssl.create_default_context()
    added = 0
    for issuer in info.get("caIssuers") or ():
        if not issuer.lower().startswith(("http://", "https://")):
            continue
        req = urllib.request.Request(issuer, headers={"User-Agent": USER_AGENT})
        with opener(req, timeout=TIMEOUT_S) as response:                    # noqa: S310
            data = response.read(200_000)
        context.load_verify_locations(cadata=data.decode("ascii") if data.lstrip().startswith(b"-----BEGIN")
                                      else ssl.DER_cert_to_PEM_cert(data))
        added += 1
    if not added:
        raise FetchError("server certificate names no issuer address")
    return context


def _incomplete_chain(exc):
    return "CERTIFICATE_VERIFY_FAILED" in str(exc) and "local issuer" in str(exc)


def _open(url, accept):
    req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": accept,
                                               "Accept-Language": "en-GB,en;q=0.8"})
    host = urllib.parse.urlsplit(url).hostname or ""
    context = _CONTEXTS.get(host)
    try:
        response = urllib.request.urlopen(req, timeout=TIMEOUT_S, context=context)  # noqa: S310 (https URLs built here)
    except urllib.error.HTTPError:
        raise
    except urllib.error.URLError as exc:
        if not _incomplete_chain(exc) or host in _CONTEXTS:
            raise
        try:
            _CONTEXTS[host] = _completed_context(host)
        except Exception as inner:  # noqa: BLE001
            _CONTEXTS[host] = None
            raise FetchError("the server sends an incomplete certificate chain and its issuer certificate could not "
                             "be fetched (%s); not fetched, verification stays on" % type(inner).__name__) from None
        response = urllib.request.urlopen(req, timeout=TIMEOUT_S, context=_CONTEXTS[host])  # noqa: S310
    with response:
        return response.status, response.geturl(), response.headers.get("Content-Type", ""), \
            response.read(MAX_BYTES + 1)[:MAX_BYTES]


class Fetcher:
    """One request a second per host, a cap per host, one retry after ten seconds on HTTP 429."""

    def __init__(self, opener=_open, sleep=time.sleep, clock=time.monotonic, min_interval=MIN_INTERVAL_S,
                 host_cap=HOST_CAP):
        self.opener, self.sleep, self.clock = opener, sleep, clock
        self.min_interval, self.host_cap = min_interval, host_cap
        self.last = {}
        self.count = {}
        self.down = {}          # host -> error, after a timeout or connection failure: not asked again this run

    def _wait(self, host):
        if self.count.get(host, 0) >= self.host_cap:
            raise FetchError("per-run cap of %d requests reached for %s" % (self.host_cap, host))
        previous = self.last.get(host)
        if previous is not None:
            gap = self.min_interval - (self.clock() - previous)
            if gap > 0:
                self.sleep(gap)
        self.last[host] = self.clock()
        self.count[host] = self.count.get(host, 0) + 1

    def get(self, url, accept="*/*"):
        """Returns (final_url, content_type, bytes). Raises FetchError."""
        host = urllib.parse.urlsplit(url).hostname or ""
        if not url.startswith("https://") or not host:
            raise FetchError("not an https URL")
        if host in self.down:
            raise FetchError(self.down[host])
        for attempt in (0, 1):
            self._wait(host)
            try:
                status, final, ctype, body = self.opener(url, accept)
                if status != 200:
                    raise FetchError("HTTP %s" % status, status)
                return final, ctype, body
            except urllib.error.HTTPError as exc:
                if exc.code == 429 and attempt == 0:
                    self.sleep(10)
                    continue
                raise FetchError("HTTP %s" % exc.code, exc.code) from None
            except FetchError:
                raise
            except Exception as exc:  # noqa: BLE001  URLError, timeouts, TLS, reset: all one failed request
                self.down[host] = "%s: %s" % (type(exc).__name__, str(exc)[:120])
                raise FetchError(self.down[host]) from None
        raise FetchError("HTTP 429", 429)


def health(source_id, url):
    return {"id": source_id, "url": url, "status": "ok", "requests": 0, "failures": 0, "items": 0, "error": ""}


def close_health(record):
    if record["requests"] == 0:
        record["status"] = "ok" if not record["error"] else "failed"
    elif record["failures"] >= record["requests"]:
        record["status"] = "failed"
    elif record["failures"]:
        record["status"] = "partial"
    return record


# ---------------------------------------------------------------- inputs

def load_projects(top_path=None, alias_path=None):
    """The 200 projects, each merged with its alias entry. Without an alias entry a derived alias is used."""
    top = json.loads(Path(top_path or HERE / "top200_solar.json").read_text(encoding="utf-8"))
    alias_file = Path(alias_path or HERE / "aliases.json")
    table = json.loads(alias_file.read_text(encoding="utf-8")).get("projects", {}) if alias_file.exists() else {}
    projects = []
    for row in top:
        ref = str(row["repd_ref"])
        entry = table.get(ref, {})
        aliases = [a for a in entry.get("aliases", []) if a and a.strip()]
        status = entry.get("alias_status", "derived")
        if not aliases:
            aliases, status = [derive_alias(row["site_name"])], "derived"
        projects.append({
            "repd_ref": ref, "rank": row["rank"], "site_name": row["site_name"].strip(),
            "operator": (row.get("operator") or "").strip(), "mw": row.get("mw"),
            "county": (row.get("county") or "").strip(), "country": row.get("country") or "",
            "planning_authority": (row.get("planning_authority") or "").strip(),
            "planning_ref": (row.get("planning_ref") or "").strip(),
            "aliases": aliases, "alias_status": status, "exclude": entry.get("exclude", []),
            "planning_file": entry.get("planning_file"),
        })
    return projects


TAIL_RE = re.compile(
    r"\s*(?:[-–,(]\s*)?(?:&|and|with|\+)?\s*\b(?:solar (?:farm|park|panels?|array|pv farm|photovoltaic array|project)"
    r"|battery(?: energy)? storage(?: system| facility)?|energy storage(?: facility| park)?|bess|co-?located"
    r"|phase \d+|solar)\b.*$", re.I)


def derive_alias(site_name):
    """"Springwell, Lincoln - Springwell Solar Farm & Battery Storage" -> "Springwell Solar Farm"."""
    name = " ".join(site_name.split())
    if " - " in name:
        left, right = [p.strip() for p in name.split(" - ", 1)]
        generic = re.match(r"(?:solar|battery|energy storage|photovoltaic|pv)\b", right, re.I)
        name = left.split(",")[0].strip() if generic else right
    name = re.sub(r"\s*&\s*(?:battery|energy)\b.*$", "", name, flags=re.I).strip(" -,")
    name = re.sub(r"^the\s+", "", name, flags=re.I)
    if not DISTINCTIVE_RE.search(name):
        name += " Solar Farm"
    return name


# ---------------------------------------------------------------- matching (contract section 3)

def _norm(text):
    text = (text or "").lower().replace("&", " and ").replace("’", "'")
    return " ".join(re.sub(r"[^a-z0-9à-ÿ']+", " ", text).split())


def phrase_in(phrase, text):
    p, t = _norm(phrase), _norm(text)
    return bool(p) and re.search(r"(?<![a-z0-9])%s(?![a-z0-9])" % re.escape(p), t) is not None


def alias_core(alias):
    """The alias without a generic tail: "Botley West Solar Farm" -> "Botley West"."""
    core = re.sub(r"\s+(?:solar|energy|renewable|pv)\b.*$", "", alias, flags=re.I).strip()
    return core if len(core) >= 4 else alias


def _facts(project):
    facts = []
    for word in re.findall(r"[A-Za-z][A-Za-z']{3,}", project.get("operator", "")):
        if word.lower() not in {"limited", "energy", "solar", "renewables", "power", "development", "partners",
                                "holdings", "group", "farm", "green", "project", "developments", "storage"}:
            facts.append(word)
    if project.get("county"):
        facts.append(project["county"])
    return facts


def match(project, title, summary=""):
    """The module's own rule (_match), then the shared title gate (gate.py): a headline placed abroad or in another
    county, or a bare name without a solar term, is not this project. The whole alias is enough in an official title."""
    return GATE.gated(project, title, _match(project, title, summary), official=True)


def _match(project, title, summary=""):
    """(basis, confidence) when the item is tied to the project by the shared rule, else None."""
    text = "%s %s" % (title, summary)
    for phrase in project.get("exclude", []):
        if phrase_in(phrase, text):
            return None
    ref = project.get("planning_ref", "")
    if ref and NATIONAL_REF_RE.fullmatch(ref) and ref.lower() in text.lower():
        return "planning reference %s in the %s" % (ref, "title" if ref.lower() in title.lower() else "summary"), \
            "confirmed"
    confidence = "confirmed" if project.get("alias_status") == "confirmed" else "uncertain"
    if GATE.inverted_solar_place(title, project):
        return "verified place alias in inverted solar-farm title", confidence
    for alias in project["aliases"]:
        distinctive = DISTINCTIVE_RE.search(alias) is not None
        if phrase_in(alias, title) and (distinctive or TOPIC_RE.search(text)):
            return "alias '%s' in the title" % alias, confidence
        core = alias_core(alias)
        if core != alias and len(_norm(core).split()) >= 2 and phrase_in(core, title) and TOPIC_RE.search(title):
            return "alias '%s' (as '%s') in the title with a solar or energy term" % (alias, core), confidence
        if phrase_in(alias, summary) and distinctive:
            for fact in _facts(project):
                if phrase_in(fact, text):
                    return "alias '%s' in the summary and '%s' agrees" % (alias, fact), confidence
    return None


def item(project, title, link, publisher, date, basis, confidence):
    link = D.canonical_link(link)
    title = D.clean_text(title, TITLE_LIMIT)
    if not link or not title:
        return None
    return {"repd_ref": project["repd_ref"], "title": title, "link": link, "publisher": publisher,
            "date": date, "family": "official", "basis": basis, "confidence": confidence}


# ---------------------------------------------------------------- source: Planning Inspectorate project list

DATE_FORMATS = ("%d/%m/%Y", "%Y-%m-%d", "%d %B %Y", "%d %b %Y", "%d-%m-%Y", "%Y-%m-%dT%H:%M:%S", "%d/%m/%Y %H:%M")


def parse_day(value):
    """A register date in any of its spellings -> YYYY-MM-DD, or None."""
    value = (value or "").strip()
    if not value:
        return None
    found = DATES.day(value)        # day first unless the value cannot be read that way; implausible years are None
    if found or re.match(r"\d{1,2}[/.\-]\d{1,2}[/.\-]\d{2,4}", value):
        return found
    iso = D.parse_date(value)
    if iso:
        return iso[:10]
    head = value.replace("Z", "").split(".")[0]
    for fmt in DATE_FORMATS:
        try:
            return dt.datetime.strptime(head, fmt).date().isoformat()
        except ValueError:
            continue
    return None


def parse_pins_csv(body):
    """Rows of the project list as dicts with: ref, name, applicant, stage, dates {column label: YYYY-MM-DD}."""
    text = body.decode("utf-8-sig", "replace") if isinstance(body, bytes) else body
    reader = csv.reader(io.StringIO(text))
    try:
        header = [h.strip() for h in next(reader)]
    except StopIteration:
        return []
    low = [h.lower() for h in header]

    def col(*needles):
        for needle in needles:
            for i, h in enumerate(low):
                if needle in h:
                    return i
        return None

    c_ref, c_name = col("project reference", "reference"), col("project name", "name")
    c_app, c_stage = col("applicant"), col("stage")
    if c_ref is None or c_name is None:
        raise ValueError("project list: no reference or name column in %r" % header[:8])
    date_cols = [i for i, h in enumerate(low) if h.startswith("date") and "anticipated" not in h]
    rows = []
    for raw in reader:
        if len(raw) <= max(c_ref, c_name):
            continue
        dates = {}
        for i in date_cols:
            day = parse_day(raw[i]) if i < len(raw) else None
            if day:
                dates[header[i]] = day
        rows.append({"ref": raw[c_ref].strip().upper(), "name": raw[c_name].strip(),
                     "applicant": raw[c_app].strip() if c_app is not None and c_app < len(raw) else "",
                     "stage": raw[c_stage].strip() if c_stage is not None and c_stage < len(raw) else "",
                     "dates": dates})
    return rows


def _milestone(label):
    label = re.sub(r"^date\s+(?:of\s+)?", "", label.strip(), flags=re.I)
    return label[:1].lower() + label[1:]


def pins_lookup(project, rows):
    """(row, how) for the project in the project list: by reference first, then by alias and applicant or topic."""
    ref = project.get("planning_ref", "").upper()
    if PINS_REF_RE.fullmatch(ref):
        for row in rows:
            if row["ref"] == ref:
                return row, "reference %s" % ref
    if "inspectorate" not in project.get("planning_authority", "").lower() and not PINS_REF_RE.fullmatch(ref):
        return None, ""
    for row in rows:
        for alias in project["aliases"]:
            if phrase_in(alias, row["name"]) or (len(_norm(alias_core(alias)).split()) >= 2
                                                 and phrase_in(alias_core(alias), row["name"])
                                                 and TOPIC_RE.search(row["name"])):
                return row, "alias '%s' is the register's project name '%s'" % (alias, row["name"])
    return None, ""


def pins_items(projects, rows, today):
    """One item per project found in the list: its newest milestone that is not in the future."""
    out, found = [], {}
    for project in projects:
        row, how = pins_lookup(project, rows)
        if not row:
            continue
        found[project["repd_ref"]] = row
        past = sorted(((day, label) for label, day in row["dates"].items() if day <= today), reverse=True)
        link = PINS_PROJECT.format(ref=row["ref"])
        if past:
            day, label = past[0]
            title = "%s: %s" % (row["name"], _milestone(label))
            if row["stage"]:
                title += " (stage: %s)" % row["stage"]
            basis = "Planning Inspectorate project list, %s; title composed from the list's '%s' and stage" % (
                how, label)
        else:
            day = None
            title = "%s: on the national infrastructure register%s" % (
                row["name"], " (stage: %s)" % row["stage"] if row["stage"] else "")
            basis = "Planning Inspectorate project list, %s; no dated milestone yet" % how
        made = item(project, title, link, "Planning Inspectorate", day, basis,
                    "confirmed" if how.startswith("reference") else "uncertain")
        if made:
            made["kind"] = "register_milestone"
            out.append(made)
    return out, found


def source_pins(projects, fetcher, today):
    record = health("pins-register", PINS_CSV)
    rows = []
    record["requests"] += 1
    try:
        _, _, body = fetcher.get(PINS_CSV, "text/csv, */*")
        rows = parse_pins_csv(body)
        if not rows:
            raise ValueError("project list is empty")
    except (FetchError, ValueError) as exc:
        record["failures"] += 1
        record["error"] = str(exc)[:200]
        return [], close_health(record), {}
    items, found = pins_items(projects, rows, today)
    record["items"] = len(items)
    record["rows"] = len(rows)
    return items, close_health(record), found


# ---------------------------------------------------------------- source: GOV.UK search API

GOVUK_FIELDS = ("title", "link", "public_timestamp", "organisations", "format", "description")


def govuk_url(query, count=20):
    params = [("q", query), ("count", str(count)), ("order", "-public_timestamp")]
    params += [("fields", f) for f in GOVUK_FIELDS]
    return GOVUK_SEARCH + "?" + urllib.parse.urlencode(params)