---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 from __future__ import annotations import argparse import html import json import math import re import subprocess import sys import time import tempfile from dataclasses import dataclass from."
resource: "https://corporate.copecheck.com"
tags: ["copecheck", "corporate", "source-file", "py"]
timestamp: "2026-05-19T10:57:15Z"
site: "corporate"
source_path: "copecheck-corporate/tools/batch_sec_reports.py"
---

# !/usr/bin/env python3

Source path: `copecheck-corporate/tools/batch_sec_reports.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-05-19T10:57:15Z`

```py
#!/usr/bin/env python3
from __future__ import annotations

import argparse
import html
import json
import math
import re
import subprocess
import sys
import time
import tempfile
from dataclasses import dataclass
from datetime import datetime, timezone
from html.parser import HTMLParser
from pathlib import Path
from typing import Any
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen


BASE = Path(__file__).resolve().parents[1]
DATA_DIR = BASE / "data"
WATCHLIST = DATA_DIR / "watchlist.json"
OUTPUT = DATA_DIR / "reports.json"

SEC_BASE = "https://data.sec.gov/submissions"
SEC_ARCHIVES = "https://www.sec.gov/Archives/edgar/data"
DEFAULT_USER_AGENT = "CopeCheck Corporate Scanner contact: btl101@gmail.com"

DEFAULT_FORMS = ["10-Q", "10-K"]
FINANCIAL_FORMS = {"10-Q", "10-K", "20-F", "40-F"}
FOREIGN_EARNINGS_FORMS = {"6-K"}

AI_TERMS = [
    "artificial intelligence",
    "generative ai",
    "genai",
    " ai ",
    "machine learning",
    "large language model",
    "llm",
    "agentic",
    "agent ",
    "agents",
    "copilot",
    "autonomous",
    "automation",
    "automated",
    "algorithmic",
    "model training",
]

LABOUR_TERMS = [
    "workforce",
    "headcount",
    "employee",
    "employees",
    "worker",
    "workers",
    "labor",
    "labour",
    "hiring",
    "layoff",
    "layoffs",
    "severance",
    "restructuring",
    "realignment",
    "productivity",
    "efficiency",
    "cost savings",
    "operating leverage",
]

CAPEX_TERMS = [
    "capital expenditure",
    "capital expenditures",
    "capex",
    "data center",
    "data centers",
    "infrastructure",
    "gpu",
    "compute",
    "cloud capacity",
    "property and equipment",
    "finance lease",
]

EUPHEMISM_TERMS = [
    "transformation",
    "reinvention",
    "empower",
    "empowering",
    "unlock",
    "accelerate",
    "streamline",
    "modernization",
    "modernisation",
    "optimize",
    "optimise",
    "customer experience",
    "operational excellence",
    "efficiency",
]

DIRECT_RISK_TERMS = [
    "replace",
    "replacing",
    "displace",
    "displacement",
    "job loss",
    "job losses",
    "unemployment",
    "redundancy",
    "redundancies",
]

SOVEREIGN_SLUGS = {"alphabet", "microsoft", "amazon", "meta", "nvidia", "apple", "oracle", "tesla"}
SERVITOR_SLUGS = {"salesforce", "servicenow", "palantir", "ibm", "adobe", "workday", "shopify", "block"}
TRANSITION_MANAGER_SLUGS = {"accenture", "goldman-sachs", "mckinsey", "deloitte", "pwc", "bcg"}
EXPOSED_PLATFORM_SLUGS = {"uber", "netflix", "spotify"}


def normalize_visible_text(text: str) -> str:
    text = html.unescape(text)
    return re.sub(r"\s+", " ", text).strip()


class TextExtractor(HTMLParser):
    def __init__(self) -> None:
        super().__init__()
        self._skip = 0
        self.parts: list[str] = []

    def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
        if tag in {"script", "style", "noscript", "svg"}:
            self._skip += 1
        if tag in {"p", "div", "br", "li", "tr", "h1", "h2", "h3", "h4"}:
            self.parts.append(" ")

    def handle_endtag(self, tag: str) -> None:
        if tag in {"script", "style", "noscript", "svg"} and self._skip:
            self._skip -= 1
        if tag in {"p", "div", "li", "tr", "h1", "h2", "h3", "h4"}:
            self.parts.append(" ")

    def handle_data(self, data: str) -> None:
        if self._skip:
            return
        text = data.strip()
        if text:
            self.parts.append(text)

    def text(self) -> str:
        joined = " ".join(self.parts)
        return normalize_visible_text(joined)


@dataclass
class FilingCandidate:
    form: str
    accession: str
    filing_date: str
    report_date: str
    primary_doc: str
    description: str


def fetch_text(url: str, user_agent: str, timeout: int = 30) -> str:
    request = Request(url, headers={"User-Agent": user_agent, "Accept-Encoding": "identity"})
    with urlopen(request, timeout=timeout) as response:
        raw = response.read(8_000_000)
        content_type = response.headers.get("content-type", "")
    if "pdf" in content_type.lower() or raw[:4] == b"%PDF":
        return extract_pdf_text(raw)
    try:
        body = raw.decode("utf-8")
    except UnicodeDecodeError:
        body = raw.decode("latin-1", errors="ignore")
    parser = TextExtractor()
    parser.feed(body)
    return parser.text()


def extract_pdf_text(raw: bytes) -> str:
    with tempfile.NamedTemporaryFile(suffix=".pdf") as pdf_file:
        pdf_file.write(raw)
        pdf_file.flush()
        try:
            result = subprocess.run(
                ["pdftotext", "-layout", pdf_file.name, "-"],
                check=False,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                timeout=45,
            )
        except (FileNotFoundError, subprocess.TimeoutExpired):
            return ""
    if result.returncode != 0:
        return ""
    return normalize_visible_text(result.stdout.decode("utf-8", errors="ignore"))


def fetch_json(url: str, user_agent: str) -> dict[str, Any]:
    request = Request(url, headers={"User-Agent": user_agent, "Accept-Encoding": "identity"})
    with urlopen(request, timeout=30) as response:
        return json.loads(response.read().decode("utf-8"))


def archive_url(cik: str, accession: str, primary_doc: str) -> str:
    cik_num = str(int(cik))
    accession_path = accession.replace("-", "")
    return f"{SEC_ARCHIVES}/{cik_num}/{accession_path}/{primary_doc}"


def filing_candidates(company: dict[str, Any], user_agent: str) -> list[FilingCandidate]:
    cik = str(company["cik"]).zfill(10)
    data = fetch_json(f"{SEC_BASE}/CIK{cik}.json", user_agent)
    recent = data.get("filings", {}).get("recent", {})
    forms = recent.get("form", [])
    accepted_forms = set(company.get("forms") or DEFAULT_FORMS)
    candidates: list[FilingCandidate] = []
    for index, form in enumerate(forms):
        if form not in accepted_forms:
            continue
        primary_doc = recent.get("primaryDocument", [""])[index]
        if not primary_doc or not primary_doc.lower().endswith((".htm", ".html", ".txt")):
            continue
        candidates.append(
            FilingCandidate(
                form=form,
                accession=recent.get("accessionNumber", [""])[index],
                filing_date=recent.get("filingDate", [""])[index],
                report_date=recent.get("reportDate", [""])[index],
                primary_doc=primary_doc,
                description=recent.get("primaryDocDescription", [""])[index] or form,
            )
        )
    return candidates


def count_terms(text: str, terms: list[str]) -> int:
    padded = f" {text.lower()} "
    return sum(padded.count(term.lower()) for term in terms)


def sentences(text: str) -> list[str]:
    chunks = re.split(r"(?<=[.!?])\s+", text)
    cleaned = []
    for chunk in chunks:
        chunk = re.sub(r"\s+", " ", chunk).strip()
        if 80 <= len(chunk) <= 380:
            cleaned.append(chunk)
    return cleaned


BOILERPLATE_EXCERPT_PATTERNS = [
    "forward-looking statements",
    "private securities litigation reform act",
    "risks and uncertainties",
    "undue reliance",
    "actual results may differ",
    "current expectations and assumptions",
    "quarterly report on form",
    "annual report on form",
]


def term_hits(sentence: str, terms: list[str]) -> int:
    lower = sentence.lower()
    hits = 0
    for term in terms:
        phrase = term.strip().lower()
        if not phrase:
            continue
        if phrase == "ai":
            hits += len(re.findall(r"\bai\b", lower))
            continue
        if phrase == "agent":
            hits += len(re.findall(r"\bagents?\b", lower))
            continue
        hits += lower.count(phrase)
    return hits


def excerpt_score(sentence: str, index: int) -> int:
    lower = sentence.lower()
    ai = term_hits(sentence, AI_TERMS)
    labour = term_hits(sentence, LABOUR_TERMS)
    capex = term_hits(sentence, CAPEX_TERMS)
    direct = term_hits(sentence, DIRECT_RISK_TERMS)
    euphemism = term_hits(sentence, EUPHEMISM_TERMS)
    categories = sum(1 for value in (ai, labour, capex, direct, euphemism) if value)
    score = ai * 4 + direct * 4 + labour * 3 + capex * 3 + euphemism
    if categories >= 2:
        score += 7
    if ai and (labour or capex or direct):
        score += 8
    if any(pattern in lower for pattern in BOILERPLATE_EXCERPT_PATTERNS):
        score -= 14
    if index < 8:
        score -= 3
    return score


def pick_excerpts(text: str) -> list[str]:
    candidates: list[tuple[int, int, str]] = []
    seen: set[str] = set()
    for index, sentence in enumerate(sentences(text)):
        score = excerpt_score(sentence, index)
        if score <= 0:
            continue
        key = sentence.lower()[:110]
        if key in seen:
            continue
        seen.add(key)
        candidates.append((score, index, sentence))
    picked = [sentence for _score, _index, sentence in sorted(candidates, key=lambda row: (-row[0], row[1]))[:4]]
    if not picked:
        picked = [
            sentence
            for sentence in sentences(text)
            if not any(pattern in sentence.lower() for pattern in BOILERPLATE_EXCERPT_PATTERNS)
        ][:3]
    return picked[:4]


def first_visible_line(text: str) -> str:
    for sentence in sentences(text):
        return sentence[:320]
    return re.sub(r"\s+", " ", text).strip()[:320]


def dt_position(company: dict[str, Any]) -> str:
    configured = company.get("dt_position")
    if configured:
        return str(configured)
    slug = company.get("slug", "")
    if slug in SOVEREIGN_SLUGS:
        return "Sovereign"
    if slug in TRANSITION_MANAGER_SLUGS:
        return "Transition Manager"
    if slug in SERVITOR_SLUGS:
        return "Servitor"
    if slug in EXPOSED_PLATFORM_SLUGS:
        return "Exposed Platform"
    return "Contested"


def signal_summary(signals: dict[str, int]) -> str:
    return (
        f"{signals.get('ai_terms', 0)} AI signals, "
        f"{signals.get('labour_terms', 0)} labour signals, "
        f"{signals.get('capex_terms', 0)} capex signals, "
        f"{signals.get('euphemism_terms', 0)} soft-framing signals and "
        f"{signals.get('direct_displacement_terms', 0)} direct displacement signals"
    )


def position_phrase(position: str) -> str:
    article = "an" if position[:1].lower() in {"a", "e", "i", "o", "u"} else "a"
    return f"{article} {position}"


def source_label(form: str, source_kind: str) -> str:
    form_upper = (form or "").upper()
    kind = (source_kind or "source").lower()
    if form_upper == "CALL" or "call" in kind or "transcript" in kind:
        return "call transcript"
    if form_upper in {"10-K", "20-F", "40-F"}:
        return "annual report"
    if form_upper in {"10-Q", "6-K"}:
        return "quarterly filing"
    if form_upper == "EARNINGS":
        return "earnings release"
    if form_upper in {"REPORT", "RESEARCH"} or "consultancy" in kind:
        return "research report"
    return kind


def pressure_line(signals: dict[str, int], position: str) -> str:
    ai = signals.get("ai_terms", 0)
    labour = signals.get("labour_terms", 0)
    capex = signals.get("capex_terms", 0)
    direct = signals.get("direct_displacement_terms", 0)
    if position == "Sovereign" and capex >= 20:
        line = "The important signal is not fear. It is accumulation: compute, cloud, model infrastructure and distribution turning cognition into a capital asset."
    elif position == "Transition Manager":
        line = "The useful signal is the business model: document the automation pressure, package the panic, then sell transition management back to the institutions causing it."
    elif position == "Servitor":
        line = "The company is trying to remain indispensable to the Sovereigns by becoming the workflow layer through which machine labour is governed, sold or verified."
    elif position == "Exposed Platform":
        line = "The platform is exposed on both sides: AI can compress its labour base and its content/customer economics at the same time."
    elif ai >= 8 and labour >= 8:
        line = "The labour signal is already inside the AI signal. Management does not need to announce job cuts for the replacement path to be visible."
    elif ai >= 4 and capex >= 8:
        line = "AI shows up as infrastructure and product investment, which keeps the employment consequence off-stage while the replacement machinery is funded."
    elif labour >= 8:
        line = "The document is labour-heavy and AI-light, which usually means automation pressure is being laundered through efficiency language."
    else:
        line = "This is a baseline entry. The omission is still useful because corporations rarely say the quiet part before the money has moved."
    if direct:
        line += " Direct displacement language appears, so the polite layer has already cracked."
    return line


def triage_paragraphs(name: str, position: str, label: str, signals: dict[str, int]) -> list[str]:
    if position == "Sovereign":
        return [
            f"{name} is not a normal patient in the AI transition. It is part of the machinery doing the surgery.",
            f"This {label} reads as Sovereign positioning: {signal_summary(signals)} arranged around compute, models, distribution and control. The post-war labour economy weakens; {name} tries to survive as a landlord of the successor regime.",
        ]
    if position == "Servitor":
        return [
            f"{name} is not safe. It is auditioning to become useful to the Sovereigns before its own customers automate around it.",
            f"This {label} shows the Servitor path: embed into workflows, sell governance and tooling, and become part of the machinery that lets fewer humans manage more output.",
        ]
    if position == "Transition Manager":
        return [
            f"{name} is not warning about the collapse from outside the room. It is selling services inside it.",
            f"This {label} is transition-management cope: quantify the pressure, rename replacement as reinvention, and turn institutional fear into billable work.",
        ]
    if position == "Exposed Platform":
        return [
            f"{name} is exposed because platforms can be squeezed by the same AI economics they hope to sell.",
            f"This {label} shows a business trying to turn automation into margin while its workers, creators, merchants or customers become easier to route around.",
        ]
    return [
        f"{name} is in the contested zone: not clearly Sovereign, not safely Servitor, and not yet honest about the labour rupture underneath the numbers.",
        f"This {label} is useful because it shows how ordinary corporate disclosure absorbs AI displacement into normal business language.",
    ]


def autopsy_paragraphs(name: str, position: str, label: str, signals: dict[str, int]) -> list[str]:
    pressure = pressure_line(signals, position)
    if position == "Sovereign":
        return [
            f"Mechanical Collapse Point: {name}'s key risk is not simply being replaced by AI. It is whether its compute, model, distribution or platform control remains a rent-bearing chokepoint once cognition becomes cheap.",
            f"Lag-Weighted Timeline: society will call this growth, productivity and cloud transformation for as long as the wage-demand circuit still looks superficially intact. The structure underneath is feudal consolidation: capital owners absorbing productive capacity while labour's role decays.",
            f"Defensive Moats: the moat is not brand warmth. It is cash, infrastructure, distribution, data, enterprise dependency, energy access and the ability to make others pay rent to the machine. {pressure}",
        ]
    if position == "Servitor":
        return [
            f"Mechanical Collapse Point: {name} collapses if its software becomes a feature inside a Sovereign-owned agent stack rather than a control layer the enterprise cannot remove.",
            "Lag-Weighted Timeline: the market will call this AI enablement while customers quietly ask why they need the old seat, licence and services model once agents do the work.",
            f"Defensive Moats: the temporary shields are workflow lock-in, compliance, data gravity, switching costs and proximity to management. {pressure}",
        ]
    if position == "Transition Manager":
        return [
            f"Mechanical Collapse Point: {name} becomes vulnerable when the same AI systems it advises on can produce decks, audits, research, implementation plans and operating-model redesign at near-zero marginal cost.",
            "Lag-Weighted Timeline: consulting survives longer than the work it describes because executives buy reassurance, liability cover and a priesthood to bless the transition.",
            f"Defensive Moats: relationships, procurement inertia, partner access and institutional fear. {pressure}",
        ]
    if position == "Exposed Platform":
        return [
            f"Mechanical Collapse Point: {name} becomes exposed when AI compresses the labour, content, support, advertising or transaction layer that made the platform valuable.",
            "Lag-Weighted Timeline: the company can report efficiency gains before the demand-side damage appears. That is the trap: margin can improve while the customer base rots.",
            f"Defensive Moats: brand, network effects, data, payments, logistics and regulatory inertia. {pressure}",
        ]
    return [
        f"Mechanical Collapse Point: {name} is exposed when AI turns its cognitive work, coordination work or customer interface into a cheaper machine-mediated process.",
        "Lag-Weighted Timeline: the admission arrives late. First comes productivity language, then restructuring, then a smaller human role treated as normal.",
        f"Defensive Moats: inertia, regulation, customer habit and legacy systems. {pressure}",
    ]


def future_scorecard(name: str, position: str) -> list[str]:
    if position == "Sovereign":
        return [
            "1 year: Strong. Capital, distribution and infrastructure protect the position.",
            "2 years: Strong but more contested. Sovereign-on-Sovereign conflict intensifies around models, energy, enterprise dependency and default interfaces.",
            "5 years: Viable if the company converts its existing moat into agentic distribution, workflow control or compute dependency.",
            "10 years: Survival depends on remaining infrastructure aristocracy. Lose the chokepoint, and the old business becomes a relic of the pre-agent web.",
        ]
    if position == "Servitor":
        return [
            "1 year: Viable. The enterprise still needs wrappers, compliance, integration and reassurance.",
            "2 years: Pressured. Seat-based software and services start to look bloated once agents can execute the underlying workflow.",
            "5 years: Survival requires becoming a control plane, verification layer or regulated workflow rail for machine labour.",
            "10 years: Either indispensable Servitor or absorbed feature. There is not much middle ground.",
        ]
    if position == "Transition Manager":
        return [
            "1 year: Strong. Panic is billable.",
            "2 years: Strong while boards still need cover, language and implementation theatre.",
            "5 years: Vulnerable as AI eats research, analysis, deck production and implementation planning.",
            "10 years: Survives only as elite transition intermediation, regulatory cover or crisis management for Sovereigns.",
        ]
    if position == "Exposed Platform":
        return [
            "1 year: Stable if automation improves margin faster than it damages demand.",
            "2 years: Mixed. AI can lower costs while weakening the labour, content or advertising base underneath the platform.",
            "5 years: Exposed unless the company owns an indispensable transaction, logistics, identity or distribution rail.",
            "10 years: Either a specialised platform tax or a hollowed-out consumer wrapper around someone else's AI stack.",
        ]
    return [
        "1 year: Stable through inertia.",
        "2 years: Pressured as AI moves from assistive tooling into workflow substitution.",
        "5 years: Exposed unless it becomes indispensable to Sovereigns or owns a hard physical/regulatory moat.",
        "10 years: Low visibility. The default path is absorption, commoditisation or managed decline.",
    ]


def survival_plan(name: str, position: str) -> list[str]:
    if position == "Sovereign":
        return [
            f"{name}'s survival path is not more AI features. It is control: own compute, models, distribution, identity, verification, payments, workflow rails and energy supply.",
            "The Sovereign move is to make other firms' productivity gains dependent on your infrastructure, then charge rent while calling it transformation.",
        ]
    if position == "Servitor":
        return [
            f"{name}'s viable path is to become indispensable plumbing for the Sovereigns: governance, workflow memory, compliance, audit, security, data integration and exception handling.",
            "Anything that remains a nice-to-have app, dashboard or seat gets eaten.",
        ]
    if position == "Transition Manager":
        return [
            f"{name}'s survival plan is Hyena's Gambit: monetise the panic, sell verification, transition intermediation, workforce redesign and liability cover.",
            "It must not merely describe the collapse. It must become the paid interpreter between executives and the machine that is shrinking their human organisation.",
        ]
    if position == "Exposed Platform":
        return [
            f"{name}'s only durable path is to own a transaction, logistics, identity, payments, content or distribution rail that AI agents still need to pass through.",
            "If it becomes only a consumer wrapper, the Sovereigns take the margin and leave the platform with support costs and political anger.",
        ]
    return [
        f"{name}'s survival path is to find a Sovereign or Servitor role. Without that, it is relying on inertia.",
        "The leverage points are energy, logistics, maintenance, regulation, verification or an owned customer rail that agents cannot bypass cheaply.",
    ]


def butcher_paragraphs(name: str, position: str, label: str) -> list[str]:
    if position == "Sovereign":
        return [
            f"{name} is not being eaten by AI. {name} is buying the machinery that eats everyone else.",
            f"This {label} is not a progress update. It is a map of rent extraction after cognition becomes cheap: own the compute, own the model layer, own the distribution, then charge the rest of the economy for access to its own replacement.",
            "Workers do not become empowered in that system. They become exception handlers, training data, compliance residue or costs waiting for the next efficiency review.",
        ]
    if position == "Servitor":
        return [
            f"{name} is trying to sell the handles on the machine that makes its customers need fewer people.",
            "That is a dangerous business and a useful one. Useful because management needs control planes. Dangerous because the same Sovereigns can turn the handle into a bundled feature.",
            "The employee hears augmentation. The CFO hears fewer seats, fewer contractors, fewer juniors, fewer excuses.",
        ]
    if position == "Transition Manager":
        return [
            f"{name} is selling a tour of the slaughterhouse with branded slides and a day rate.",
            "The trick is simple: describe the automation pressure clearly enough to scare the buyer, then refuse to name the end state clearly enough to threaten the invoice.",
            "Reskilling is the lullaby. Transformation is the anaesthetic. The work still goes into the machine.",
        ]
    if position == "Exposed Platform":
        return [
            f"{name} wants AI to be a margin story. The ugly risk is that AI turns the platform into a thinner toll booth on a poorer customer base.",
            "Automation can make the numbers look cleaner while the social substrate gets worse. That is how platforms rot politely.",
            "The company gets efficiency. The worker, creator, merchant or customer gets squeezed and told it is personalisation.",
        ]
    return [
        f"{name} is giving the polite version. The impolite version is that another chunk of human coordination is being priced against software.",
        "The document sounds dry because the violence is administrative: line item, platform migration, workflow redesign, headcount discipline.",
    ]


def oracle_protocol_sections(
    company: dict[str, Any],
    title: str,
    score: int,
    band: str,
    signals: dict[str, int],
    source_kind: str,
    form: str,
) -> list[dict[str, Any]]:
    name = company.get("name", "This source")
    position = dt_position(company)
    label = source_label(form, source_kind)
    pressure = pressure_line(signals, position)

    return [
        {"title": "The Triage", "paragraphs": triage_paragraphs(name, position, label, signals)},
        {"title": "The Autopsy", "paragraphs": autopsy_paragraphs(name, position, label, signals)},
        {"title": "Future-Proofing Scorecard", "paragraphs": future_scorecard(name, position)},
        {"title": "Survival Plan", "paragraphs": survival_plan(name, position)},
        {"title": "The Butcher's Version", "paragraphs": butcher_paragraphs(name, position, label)},
        {
            "title": "Final Verdict",
            "paragraphs": [
                f"{name} scores {score}/100: {band}. {pressure}",
                "The score does not mean the company is necessarily dying. It measures how clearly this source exposes the successor system: AI dominance, productive participation collapse, coordination failure, and the scramble to become Sovereign, Servitor or paid guide through the wreckage.",
            ],
        },
    ]


def oracle_lines(
    company: dict[str, Any],
    score: int,
    band: str,
    signals: dict[str, int],
    source_kind: str,
    form: str,
) -> tuple[str, str]:
    name = company.get("name", "This company")
    form_upper = (form or "").upper()
    kind = (source_kind or "").lower()
    position = dt_position(company)
    if position == "Sovereign":
        killer = f"{name} is not being eaten by AI. It is building the machinery that eats everyone else."
    elif position == "Servitor":
        killer = f"{name} is trying to become indispensable to the Sovereigns before the agent stack turns it into a feature."
    elif position == "Transition Manager":
        killer = f"{name} is selling the operating manual for the collapse as transformation strategy."
    elif position == "Exposed Platform":
        killer = f"{name} wants AI to be a margin story, but the same machine can hollow out the platform underneath it."
    elif form_upper == "CALL" or "transcript" in kind or "call" in kind:
        killer = f"{name} is not selling productivity. It is auditioning synthetic labour in front of investors and calling the handover transformation."
    elif form_upper == "EARNINGS":
        killer = f"{name}'s earnings release says growth; the machinery underneath says fewer humans per unit of output."
    else:
        killer = f"{name} is converting human work into managed machine throughput and calling the paperwork progress."

    share = (
        f"{killer} Corporate Cope scores it {score}/100: {band}, with "
        f"{signals.get('ai_terms', 0)} AI signals, {signals.get('labour_terms', 0)} labour signals and "
        f"{signals.get('capex_terms', 0)} capex signals. This is {position_phrase(position)} diagnosis, not a normal equity read."
    )
    return killer, share


def score_text(company: dict[str, Any], title: str, text: str, source_kind: str = "report", form: str = "REPORT") -> dict[str, Any]:
    ai = count_terms(text, AI_TERMS)
    labour = count_terms(text, LABOUR_TERMS)
    capex = count_terms(text, CAPEX_TERMS)
    euphemism = count_terms(text, EUPHEMISM_TERMS)
    direct = count_terms(text, DIRECT_RISK_TERMS)

    # SEC reports are long and repetitive. Use logarithmic scoring so the
    # index reads posture and co-occurrence rather than raw document length.
    score = 16
    score += min(math.log1p(ai) * 5.6, 20)
    score += min(math.log1p(labour) * 3.2, 14)
    score += min(math.log1p(capex) * 3.4, 14)
    score += min(math.log1p(euphemism) * 2.4, 7)
    if ai >= 4 and labour >= 8:
        score += 6
    if ai >= 4 and capex >= 8:
        score += 5
    if direct:
        score += min(math.log1p(direct) * 2.8, 7)
    sector = company.get("sector", "").lower()
    if any(term in sector for term in ("consulting", "workflow", "automation", "ai infrastructure", "enterprise software")):
        score += 4
    if company.get("slug") in {"nvidia", "palantir", "servicenow", "salesforce", "microsoft", "meta", "amazon"}:
        score += 4
    position = dt_position(company)
    if position == "Sovereign" and (ai >= 4 or capex >= 8):
        score += 5
    elif position == "Servitor" and (ai >= 4 or labour >= 8):
        score += 4
    elif position == "Transition Manager":
        score += 5
    elif position == "Exposed Platform" and (ai >= 4 or labour >= 8):
        score += 2
    if form.upper() == "CALL" or "transcript" in source_kind.lower():
        score += 8
    elif form.upper() in {"10-K", "20-F", "40-F"}:
        score += 4
    elif form.upper() == "EARNINGS":
        score += 3
    if ai == 0 and direct == 0:
        score -= 10
    cap = 96 if form.upper() == "CALL" or "transcript" in source_kind.lower() or position == "Sovereign" else 92
    score = int(max(12, min(cap, round(score))))

    if score >= 82:
        band = "TERMINAL COPIUM"
        band_slug = "terminal"
    elif score >= 64:
        band = "HEAVY COPE"
        band_slug = "heavy"
    elif score >= 44:
        band = "MODERATE COPE"
        band_slug = "moderate"
    else:
        band = "LIGHT COPE"
        band_slug = "light"

    signals = {
        "ai_terms": ai,
        "labour_terms": labour,
        "capex_terms": capex,
        "euphemism_terms": euphemism,
        "direct_displacement_terms": direct,
    }

    if ai and labour:
        angle = "AI and labour language appear in the same report, but the corporate framing routes the pressure through productivity, efficiency or transformation."
    elif ai and capex:
        angle = "AI shows up mainly as infrastructure and product investment, which keeps the labour question off-stage while the replacement machinery is funded."
    elif labour and not ai:
        angle = "The report contains workforce and efficiency language without naming AI as the structural driver."
    elif ai:
        angle = "The report celebrates AI capability while avoiding the employment consequences."
    else:
        angle = "The report is not heavily AI-coded yet, but it still belongs in the archive as a baseline corporate disclosure."

    verdict = (
        f"{company['name']} scores {score}/100 as {position_phrase(position)} diagnosis, not a normal equity read. "
        f"The source exposes how AI-capital, labour pressure, capex, workflow control or transition-management language is being folded into ordinary corporate reporting. {angle}"
    )

    signals = {
        "ai_terms": ai,
        "labour_terms": labour,
        "capex_terms": capex,
        "euphemism_terms": euphemism,
        "direct_displacement_terms": direct,
    }

    killer_line, share_line = oracle_lines(company, score, band, signals, source_kind, form)

    return {
        "score": score,
        "band": band,
        "band_slug": band_slug,
        "signals": signals,
        "oracle_protocol": "oracle-of-obsolescence-v4.5-content-dump-authority-corporate",
        "protocol_scan": {
            "kind": "URL",
            "title": title,
            "first_line": first_visible_line(text),
        },
        "oracle_sections": oracle_protocol_sections(company, title, score, band, signals, source_kind, form),
        "oracle_verdict": verdict,
        "killer_line": killer_line,
        "share_line": share_line,
        "excerpts": pick_excerpts(text),
    }


def apply_minimum_score(scored: dict[str, Any], minimum: int | None) -> dict[str, Any]:
    if minimum is None or scored["score"] >= minimum:
        return scored
    scored = dict(scored)
    scored["score"] = min(int(minimum), 92)
    if scored["score"] >= 82:
        scored["band"] = "TERMINAL COPIUM"
        scored["band_slug"] = "terminal"
    elif scored["score"] >= 64:
        scored["band"] = "HEAVY COPE"
        scored["band_slug"] = "heavy"
    elif scored["score"] >= 44:
        scored["band"] = "MODERATE COPE"
        scored["band_slug"] = "moderate"
    else:
        scored["band"] = "LIGHT COPE"
        scored["band_slug"] = "light"
    scored["oracle_verdict"] = re.sub(
        r"scores \d+/100",
        f"scores {scored['score']}/100",
        scored["oracle_verdict"],
        count=1,
    )
    scored = refresh_score_mentions(scored)
    return scored


def band_for_score(score: int) -> tuple[str, str]:
    if score >= 82:
        return "TERMINAL COPIUM", "terminal"
    if score >= 64:
        return "HEAVY COPE", "heavy"
    if score >= 44:
        return "MODERATE COPE", "moderate"
    return "LIGHT COPE", "light"


def source_weight(form: str, source_kind: str) -> int:
    form_upper = (form or "").upper()
    kind = (source_kind or "").lower()
    if form_upper == "CALL" or "transcript" in kind or "call" in kind:
        return 5
    if form_upper in {"10-K", "20-F", "40-F"}:
        return 4
    if form_upper in {"REPORT", "RESEARCH"} or "consultancy" in kind:
        return 4
    if form_upper == "EARNINGS" or "earnings" in kind:
        return 3
    if form_upper in {"10-Q", "6-K"}:
        return 2
    return 1


def report_rank_score(score: int, form: str, source_kind: str) -> int:
    return int(score or 0) + source_weight(form, source_kind) * 5


def refresh_score_mentions(scored: dict[str, Any]) -> dict[str, Any]:
    score = int(scored.get("score") or 0)
    band = scored.get("band") or band_for_score(score)[0]
    sections = scored.get("oracle_sections") or []
    if not sections:
        return scored
    refreshed = []
    for section in sections:
        item = dict(section)
        paragraphs = item.get("paragraphs") or []
        if isinstance(paragraphs, str):
            paragraphs = [paragraphs]
        item["paragraphs"] = [
            re.sub(r"scores \d+/100(?:: [A-Z ]+)?", f"scores {score}/100: {band}", paragraph)
            for paragraph in paragraphs
        ]
        refreshed.append(item)
    scored["oracle_sections"] = refreshed
    return scored


def apply_report_overrides(scored: dict[str, Any], report: dict[str, Any]) -> dict[str, Any]:
    scored = apply_minimum_score(scored, report.get("minimum_score"))
    if not any(key in report for key in ("fixed_score", "oracle_verdict", "killer_line", "share_line", "oracle_takeaways", "oracle_sections", "excerpts")):
        return scored
    scored = dict(scored)
    if report.get("fixed_score") is not None:
        scored["score"] = int(report["fixed_score"])
        scored["band"], scored["band_slug"] = band_for_score(scored["score"])
        scored = refresh_score_mentions(scored)
    if report.get("oracle_verdict"):
        scored["oracle_verdict"] = report["oracle_verdict"]
    if report.get("killer_line"):
        scored["killer_line"] = report["killer_line"]
    if report.get("share_line"):
        scored["share_line"] = report["share_line"]
    if report.get("oracle_takeaways"):
        scored["oracle_takeaways"] = report["oracle_takeaways"]
    if report.get("oracle_sections"):
        scored["oracle_sections"] = report["oracle_sections"]
    if report.get("excerpts"):
        scored["excerpts"] = report["excerpts"]
    return scored


def report_title(company: dict[str, Any], filing: FilingCandidate) -> str:
    date_bits = []
    if filing.report_date:
        date_bits.append(f"period ended {filing.report_date}")
    if filing.filing_date:
        date_bits.append(f"filed {filing.filing_date}")
    suffix = ", ".join(date_bits)
    return f"{company['name']} {filing.form}" + (f" ({suffix})" if suffix else "")


def filing_override(company: dict[str, Any], report_id: str, filing: FilingCandidate) -> dict[str, Any]:
    for override in company.get("filing_overrides", []):
        if override.get("id") == report_id:
            return override
        if override.get("form") == filing.form and override.get("report_date") == filing.report_date:
            return override
        if override.get("form") == filing.form and override.get("filing_date") == filing.filing_date:
            return override
    return {}


def build_report_row(
    company: dict[str, Any],
    report_id: str,
    title: str,
    source_kind_value: str,
    form_value: str,
    filing_date: str,
    report_date: str,
    url: str,
    accession: str,
    word_count: int,
    scored: dict[str, Any],
) -> dict[str, Any]:
    weight = source_weight(form_value, source_kind_value)
    return {
        "id": report_id,
        "company_slug": company["slug"],
        "company_name": company["name"],
        "ticker": company.get("ticker"),
        "sector": company.get("sector"),
        "title": title,
        "source_kind": source_kind_value,
        "form": form_value,
        "dt_position": dt_position(company),
        "filing_date": filing_date,
        "report_date": report_date,
        "url": url,
        "accession": accession,
        "word_count": word_count,
        "source_weight": weight,
        "rank_score": report_rank_score(int(scored.get("score") or 0), form_value, source_kind_value),
        "why_watch": company.get("why_watch", ""),
        **scored,
    }


def process_company(company: dict[str, Any], limit: int, transcript_limit: int, user_agent: str) -> tuple[list[dict[str, Any]], list[str]]:
    reports: list[dict[str, Any]] = []
    errors: list[str] = []
    regular_reports = 0

    for index, transcript in enumerate(company.get("transcript_sources", [])[:transcript_limit], start=1):
        try:
            text = fetch_text(transcript["url"], user_agent)
        except (HTTPError, URLError, TimeoutError) as exc:
            errors.append(f"{company['name']} transcript {transcript.get('url')}: {exc}")
            continue
        except Exception as exc:
            errors.append(f"{company['name']} transcript {transcript.get('url')}: {type(exc).__name__}: {exc}")
            continue
        if len(text) < 700:
            errors.append(f"{company['name']} transcript {transcript.get('url')}: extracted too little text")
            continue
        source_kind_value = transcript.get("source_kind", "earnings call transcript")
        form_value = transcript.get("form", "CALL")
        scored = apply_report_overrides(
            score_text(company, transcript["title"], text[:220_000], source_kind_value, form_value),
            transcript,
        )
        published_at = transcript.get("published_at", "")
        report_id = transcript.get("id") or f"{company['slug']}-call-{published_at or index}"
        reports.append(
            build_report_row(
                company,
                report_id,
                transcript["title"],
                source_kind_value,
                form_value,
                published_at,
                published_at,
                transcript["url"],
                "",
                len(text.split()),
                scored,
            )
        )
        time.sleep(0.12)

    for index, manual in enumerate(company.get("manual_reports", [])[:limit], start=1):
        try:
            text = fetch_text(manual["url"], user_agent)
        except (HTTPError, URLError, TimeoutError) as exc:
            errors.append(f"{company['name']} manual report {manual.get('url')}: {exc}")
            continue
        except Exception as exc:
            errors.append(f"{company['name']} manual report {manual.get('url')}: {type(exc).__name__}: {exc}")
            continue
        if len(text) < 700:
            errors.append(f"{company['name']} manual report {manual.get('url')}: extracted too little text")
            continue
        scored = apply_report_overrides(
            score_text(
                company,
                manual["title"],
                text[:180_000],
                manual.get("source_kind", "earnings press release"),
                manual.get("form", "EARNINGS"),
            ),
            manual,
        )
        published_at = manual.get("published_at", "")
        reports.append(
            build_report_row(
                company,
                manual.get("id") or f"{company['slug']}-earnings-{published_at or index}",
                manual["title"],
                manual.get("source_kind", "earnings press release"),
                manual.get("form", "EARNINGS"),
                published_at,
                published_at,
                manual["url"],
                "",
                len(text.split()),
                scored,
            )
        )
        regular_reports += 1
        time.sleep(0.12)
    if regular_reports >= limit:
        return reports, errors

    for filing in filing_candidates(company, user_agent):
        if regular_reports >= limit:
            break
        url = archive_url(company["cik"], filing.accession, filing.primary_doc)
        try:
            text = fetch_text(url, user_agent)
        except (HTTPError, URLError, TimeoutError) as exc:
            errors.append(f"{company['name']} {filing.accession}: {exc}")
            continue
        except Exception as exc:  # defensive: one broken filing should not stop the batch
            errors.append(f"{company['name']} {filing.accession}: {type(exc).__name__}: {exc}")
            continue
        if len(text) < 1500:
            errors.append(f"{company['name']} {filing.accession}: extracted too little text")
            continue
        title = report_title(company, filing)
        report_id = f"{company['slug']}-{filing.form.lower().replace('-', '')}-{filing.report_date or filing.filing_date}".strip("-")
        scored = apply_report_overrides(
            score_text(company, title, text[:240_000], "SEC filing", filing.form),
            filing_override(company, report_id, filing),
        )
        reports.append(
            build_report_row(
                company,
                report_id,
                title,
                "SEC filing",
                filing.form,
                filing.filing_date,
                filing.report_date,
                url,
                filing.accession,
                len(text.split()),
                scored,
            )
        )
        regular_reports += 1
        time.sleep(0.12)
    for index, manual in enumerate(company.get("extra_reports", []), start=1):
        try:
            text = fetch_text(manual["url"], user_agent)
        except Exception as exc:
            errors.append(f"{company['name']} extra report {manual.get('url')}: {type(exc).__name__}: {exc}")
            continue
        if len(text) < 700:
            errors.append(f"{company['name']} extra report {manual.get('url')}: extracted too little text")
            continue
        scored = apply_report_overrides(
            score_text(
                company,
                manual["title"],
                text[:180_000],
                manual.get("source_kind", "research report"),
                manual.get("form", "RESEARCH"),
            ),
            manual,
        )
        published_at = manual.get("published_at", "")
        reports.append(
            build_report_row(
                company,
                manual.get("id") or f"{company['slug']}-research-{index}",
                manual["title"],
                manual.get("source_kind", "research report"),
                manual.get("form", "RESEARCH"),
                published_at,
                published_at,
                manual["url"],
                "",
                len(text.split()),
                scored,
            )
        )
        time.sleep(0.12)
    return reports, errors


def curated_score(source: dict[str, Any], report: dict[str, Any]) -> dict[str, Any]:
    text = " ".join([source.get("name", ""), source.get("why_watch", ""), report.get("title", "")])
    fake_company = {
        "name": source.get("name", "Consultancy"),
        "slug": source.get("slug", ""),
        "sector": source.get("sector", ""),
        "dt_position": source.get("dt_position", "Transition Manager"),
    }
    scored = score_text(fake_company, report.get("title", ""), text * 8, "consultancy report scanner", "REPORT")
    score = max(scored["score"], 68)
    if source["slug"] in {"mckinsey", "pwc", "bcg"}:
        score = max(score, 74)
    if "replaces" in report.get("title", "").lower():
        score = max(score, 78)
    scored["score"] = min(score, 88)
    scored["band"] = "HEAVY COPE" if scored["score"] < 82 else "TERMINAL COPIUM"
    scored["band_slug"] = "heavy" if scored["score"] < 82 else "terminal"
    scored["oracle_sections"] = oracle_protocol_sections(
        fake_company,
        report.get("title", ""),
        scored["score"],
        scored["band"],
        scored.get("signals", {}),
        "consultancy report scanner",
        "REPORT",
    )
    scored["oracle_verdict"] = (
        f"{source['name']} scores {scored['score']}/100 as a Transition Manager diagnosis. "
        "The report source belongs to the consultancy pattern: document the automation pressure, then sell transformation, reskilling or operating-model redesign as the soft landing."
    )
    scored["killer_line"], scored["share_line"] = oracle_lines(
        fake_company,
        scored["score"],
        scored["band"],
        scored.get("signals", {}),
        "consultancy report scanner",
        "REPORT",
    )
    scored["excerpts"] = [
        source.get("why_watch", ""),
        "Private consultancies do not publish normal quarterly earnings filings, so Corporate Cope treats this as a report-scanner entry rather than an earnings entry.",
    ]
    return scored


def build_consultancy_reports(watchlist: dict[str, Any]) -> list[dict[str, Any]]:
    rows: list[dict[str, Any]] = []
    for source in watchlist.get("consultancy_sources", []):
        for index, report in enumerate(source.get("reports", [])[:2], start=1):
            scored = curated_score(source, report)
            rows.append(
                {
                    "id": f"{source['slug']}-report-{index}",
                    "company_slug": source["slug"],
                    "company_name": source["name"],
                    "ticker": None,
                    "sector": source.get("sector"),
                    "title": report.get("title", source["name"]),
                    "source_kind": "consultancy report scanner",
                    "form": "REPORT",
                    "dt_position": dt_position(source),
                    "filing_date": "",
                    "report_date": "",
                    "url": report.get("url", ""),
                    "accession": "",
                    "word_count": 0,
                    "source_weight": source_weight("REPORT", "consultancy report scanner"),
                    "rank_score": report_rank_score(scored["score"], "REPORT", "consultancy report scanner"),
                    "why_watch": source.get("why_watch", ""),
                    **scored,
                }
            )
    return rows


def company_summaries(companies: list[dict[str, Any]], reports: list[dict[str, Any]]) -> list[dict[str, Any]]:
    by_slug: dict[str, list[dict[str, Any]]] = {}
    for report in reports:
        by_slug.setdefault(report["company_slug"], []).append(report)
    rows = []
    for company in companies:
        company_reports = by_slug.get(company["slug"], [])
        avg = round(sum(r["score"] for r in company_reports) / len(company_reports), 1) if company_reports else 0
        latest = max((r.get("filing_date") or r.get("report_date") or "" for r in company_reports), default="")
        transcript_count = sum(1 for r in company_reports if r.get("form") == "CALL")
        rows.append(
            {
                "slug": company["slug"],
                "name": company["name"],
                "ticker": company.get("ticker"),
                "sector": company.get("sector"),
                "dt_position": dt_position(company),
                "ir_url": company.get("ir_url"),
                "why_watch": company.get("why_watch", ""),
                "report_count": len(company_reports),
                "transcript_count": transcript_count,
                "average_score": avg,
                "latest_date": latest,
                "source_mode": "mixed" if transcript_count else "sec",
            }
        )
    return rows


def normalized_url(value: str) -> str:
    return re.sub(r"/+$", "", (value or "").strip()).lower()


def dedupe_reports(reports: list[dict[str, Any]]) -> list[dict[str, Any]]:
    best: dict[str, dict[str, Any]] = {}
    for report in reports:
        key = normalized_url(report.get("url", "")) or report.get("id", "")
        current = best.get(key)
        if not current:
            best[key] = report
            continue
        current_rank = (current.get("rank_score") or current.get("score") or 0, current.get("filing_date") or "")
        report_rank = (report.get("rank_score") or report.get("score") or 0, report.get("filing_date") or "")
        if report_rank > current_rank:
            best[key] = report
    return list(best.values())


def main() -> int:
    parser = argparse.ArgumentParser(description="Batch pull and score Corporate Cope filings")
    parser.add_argument("--limit", type=int, default=2, help="reports per public company")
    parser.add_argument("--transcript-limit", type=int, default=2, help="official call transcripts per public company")
    parser.add_argument("--company", action="append", help="slug to process; can be supplied multiple times")
    parser.add_argument("--user-agent", default=DEFAULT_USER_AGENT)
    args = parser.parse_args()

    watchlist = json.loads(WATCHLIST.read_text(encoding="utf-8"))
    companies = watchlist.get("public_companies", [])
    if args.company:
        wanted = set(args.company)
        companies = [company for company in companies if company["slug"] in wanted]
        if not companies:
            print("No matching company slugs.", file=sys.stderr)
            return 2

    all_reports: list[dict[str, Any]] = []
    errors: list[str] = []
    for company in companies:
        print(f"Scanning {company['name']}...", file=sys.stderr)
        reports, company_errors = process_company(company, args.limit, args.transcript_limit, args.user_agent)
        all_reports.extend(reports)
        errors.extend(company_errors)

    consultancy_reports = build_consultancy_reports(watchlist)
    all_reports.extend(consultancy_reports)
    all_reports = dedupe_reports(all_reports)
    all_reports.sort(key=lambda row: (row.get("filing_date") or row.get("report_date") or "0000-00-00", row["company_name"]), reverse=True)

    company_rows = company_summaries(watchlist.get("public_companies", []), all_reports)
    existing_slugs = {company["slug"] for company in watchlist.get("public_companies", [])}
    for source in watchlist.get("consultancy_sources", []):
        if source["slug"] in existing_slugs:
            continue
        source_reports = [r for r in all_reports if r["company_slug"] == source["slug"]]
        avg = round(sum(r["score"] for r in source_reports) / len(source_reports), 1) if source_reports else 0
        company_rows.append(
            {
                "slug": source["slug"],
                "name": source["name"],
                "ticker": None,
                "sector": source.get("sector"),
                "dt_position": dt_position(source),
                "ir_url": None,
                "why_watch": source.get("why_watch", ""),
                "report_count": len(source_reports),
                "transcript_count": 0,
                "average_score": avg,
                "latest_date": "",
                "source_mode": "curated",
            }
        )

    payload = {
        "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z"),
        "report_limit_per_company": args.limit,
        "companies": company_rows,
        "reports": all_reports,
        "errors": errors,
        "method": {
            "public_companies": "Latest regular SEC financial filings, usually 10-Q/10-K. Foreign issuers use 6-K/20-F/40-F when configured.",
            "transcripts": "Official investor-relations call transcripts are configured per company in watchlist.json under transcript_sources and are processed before filings.",
            "consultancies": "Curated report-scanner entries because private consultancies do not publish normal quarterly earnings filings.",
            "scoring": "Deterministic first-pass signal score over AI, labour, capex, euphemism and displacement terms, plus source weighting so call transcripts and annual reports outrank generic filings. Designed for cheap batch triage before any model escalation.",
        },
    }
    OUTPUT.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(f"Wrote {len(all_reports)} reports for {len(company_rows)} sources to {OUTPUT}", file=sys.stderr)
    if errors:
        print(f"{len(errors)} non-fatal fetch/extract errors recorded in reports.json", file=sys.stderr)
    return 0


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