---
type: "Source File"
title: "from __future__ import annotations"
description: "from __future__ import annotations import argparse import html import json import os from datetime import datetime, timezone from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path."
resource: "https://corporate.copecheck.com"
tags: ["copecheck", "corporate", "source-file", "py"]
timestamp: "2026-09-26T10:09:14Z"
site: "corporate"
source_path: "copecheck-corporate/server.py"
---

# from __future__ import annotations

Source path: `copecheck-corporate/server.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-09-26T10:09:14Z`

```py
from __future__ import annotations

import argparse
import html
import json
import os
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import quote, urlparse


BASE = Path(__file__).resolve().parent
DATA_DIR = BASE / "data"
REPORTS_FILE = Path(os.getenv("CORPORATE_REPORTS_FILE", str(DATA_DIR / "reports.json")))
PUBLIC_BASE = os.getenv("COPECHECK_CORPORATE_PUBLIC_BASE", "https://corporate.copecheck.com").rstrip("/")


def esc(value: object) -> str:
    return html.escape("" if value is None else str(value), quote=True)


def load_data() -> dict:
    if not REPORTS_FILE.exists():
        return {"generated_at": "", "companies": [], "reports": [], "errors": []}
    return json.loads(REPORTS_FILE.read_text(encoding="utf-8"))


def score_class(score: int | float) -> str:
    score = int(score or 0)
    if score >= 82:
        return "terminal"
    if score >= 64:
        return "heavy"
    if score >= 44:
        return "moderate"
    return "light"


def fmt_date(value: str | None) -> str:
    if not value:
        return "Undated"
    return value


def form_label(report: dict) -> str:
    form = str(report.get("form") or "").upper()
    labels = {
        "CALL": "earnings call transcript",
        "EARNINGS": "earnings release",
        "REPORT": "report",
        "RESEARCH": "research note",
    }
    return labels.get(form, form or "report")


def company_map(data: dict) -> dict[str, dict]:
    return {company["slug"]: company for company in data.get("companies", [])}


def reports_for(data: dict, slug: str) -> list[dict]:
    return [report for report in data.get("reports", []) if report.get("company_slug") == slug]


def report_by_id(data: dict, report_id: str) -> dict | None:
    for report in data.get("reports", []):
        if report.get("id") == report_id:
            return report
    return None


CSS = """
:root {
  color-scheme: light;
  --bg: #f5f2ed;
  --paper: #ffffff;
  --ink: #161514;
  --muted: #665f57;
  --soft: #8b8176;
  --line: #ded6cc;
  --line-strong: #c8bdb0;
  --red: #b32635;
  --amber: #b06d10;
  --green: #0f766e;
  --blue: #245c9c;
  --shadow: 0 18px 46px rgba(32, 28, 24, .08);
  font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
* { box-sizing: border-box; }
body {
  margin: 0;
  background:
    linear-gradient(180deg, rgba(255,255,255,.84), rgba(245,242,237,.9) 420px),
    var(--bg);
  color: var(--ink);
  line-height: 1.5;
}
a { color: inherit; text-underline-offset: .18em; }
.shell { width: min(1180px, calc(100% - 32px)); margin: 0 auto; }
.topbar {
  position: sticky;
  top: 0;
  z-index: 10;
  border-bottom: 1px solid var(--line);
  background: rgba(255,255,255,.88);
  backdrop-filter: blur(14px);
}
.topbar .shell {
  min-height: 64px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 18px;
}
.brand { display: inline-flex; align-items: center; gap: 10px; font-weight: 760; text-decoration: none; }
.mark {
  width: 32px;
  height: 32px;
  border: 2px solid var(--ink);
  display: grid;
  place-items: center;
  font-size: 12px;
  letter-spacing: 0;
}
nav { display: flex; align-items: center; gap: 16px; flex-wrap: wrap; color: var(--muted); font-size: 14px; }
nav a { text-decoration: none; }
nav a:hover { color: var(--ink); }
.hero {
  padding: 56px 0 28px;
  display: grid;
  grid-template-columns: minmax(0, 1fr) 360px;
  gap: 34px;
  align-items: end;
}
h1 {
  font-size: clamp(44px, 7vw, 86px);
  line-height: .92;
  letter-spacing: 0;
  margin: 0 0 20px;
  max-width: 870px;
}
.lead {
  color: var(--muted);
  font-size: clamp(18px, 2vw, 22px);
  max-width: 760px;
  margin: 0;
}
.hero-panel {
  border: 1px solid var(--line-strong);
  background: var(--paper);
  box-shadow: var(--shadow);
  padding: 22px;
}
.hero-panel .big {
  font-size: 42px;
  line-height: 1;
  font-weight: 820;
}
.hero-panel .label { color: var(--muted); font-size: 13px; margin-top: 8px; }
.metrics {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 12px;
  margin-top: 26px;
  margin-bottom: 34px;
}
.metric {
  border-top: 1px solid var(--line);
  padding-top: 14px;
}
.metric strong { display: block; font-size: 28px; line-height: 1; }
.metric span { color: var(--muted); font-size: 13px; }
.section {
  padding: 28px 0;
  border-top: 1px solid var(--line);
}
.section-head {
  display: flex;
  align-items: end;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 18px;
}
h2 { font-size: clamp(28px, 4vw, 44px); line-height: 1; letter-spacing: 0; margin: 0; }
.section-head p { color: var(--muted); margin: 0; max-width: 580px; }
.company-grid {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 12px;
}
.company-card,
.report-card,
.method-card {
  background: var(--paper);
  border: 1px solid var(--line);
  padding: 18px;
  box-shadow: 0 8px 24px rgba(32,28,24,.045);
}
.company-card {
  display: grid;
  grid-template-columns: 74px minmax(0, 1fr);
  gap: 14px;
  text-decoration: none;
}
.score {
  height: 66px;
  border: 1px solid var(--line-strong);
  display: grid;
  place-items: center;
  font-weight: 820;
  font-size: 24px;
  background: #faf9f7;
}
.score.terminal { color: var(--red); border-color: rgba(179,38,53,.35); background: rgba(179,38,53,.08); }
.score.heavy { color: var(--amber); border-color: rgba(176,109,16,.35); background: rgba(176,109,16,.1); }
.score.moderate { color: var(--blue); border-color: rgba(36,92,156,.32); background: rgba(36,92,156,.08); }
.score.light { color: var(--green); border-color: rgba(15,118,110,.32); background: rgba(15,118,110,.08); }
.company-card h3,
.report-card h3 { margin: 0; font-size: 18px; line-height: 1.15; }
.meta {
  color: var(--soft);
  font-size: 12px;
  margin-top: 6px;
  text-transform: uppercase;
  letter-spacing: .04em;
}
.why { color: var(--muted); margin: 10px 0 0; font-size: 14px; }
.report-list {
  display: grid;
  gap: 12px;
}
.report-card {
  display: grid;
  grid-template-columns: 82px minmax(0, 1fr) auto;
  gap: 16px;
  align-items: start;
}
.spotlight {
  background: var(--ink);
  color: #fff;
  border: 0;
  padding: 24px;
  box-shadow: var(--shadow);
}
.spotlight .meta,
.spotlight .verdict,
.spotlight .why { color: rgba(255,255,255,.72); }
.spotlight h2 {
  color: #fff;
  font-size: clamp(34px, 5vw, 64px);
}
.spotlight .oracle-line {
  border-color: rgba(255,255,255,.22);
  background: rgba(255,255,255,.08);
  color: #fff;
}
.spotlight .button { background: transparent; color: #fff; border-color: rgba(255,255,255,.38); }
.spotlight .button.primary { background: #fff; color: var(--ink); border-color: #fff; }
.verdict { color: var(--muted); margin: 10px 0 0; }
.oracle-line {
  border: 1px solid rgba(179, 38, 53, .24);
  background: rgba(179, 38, 53, .075);
  color: var(--ink);
  padding: 16px;
  margin: 14px 0 0;
  font-size: clamp(18px, 2vw, 23px);
  line-height: 1.22;
  font-weight: 780;
}
.takeaways {
  display: grid;
  gap: 10px;
  margin-top: 14px;
}
.takeaway {
  border: 1px solid var(--line);
  background: #faf9f7;
  padding: 12px 14px;
  color: var(--muted);
}
.protocol-scan {
  border: 1px solid var(--line-strong);
  background: #fbfaf8;
  padding: 14px;
  margin: 0 0 22px;
  color: var(--muted);
  font-size: 13px;
}
.protocol-scan strong {
  color: var(--ink);
  display: block;
  font-size: 12px;
  letter-spacing: .04em;
  text-transform: uppercase;
}
.protocol-scan p { margin: 8px 0 0; }
.oracle-essay {
  display: grid;
  gap: 22px;
  margin-top: 26px;
}
.oracle-section {
  border-top: 1px solid var(--line);
  padding-top: 18px;
}
.oracle-section h2 {
  margin: 0 0 10px;
  font-size: 26px;
}
.oracle-section p {
  margin: 0 0 12px;
  color: var(--ink);
  font-size: 17px;
  line-height: 1.68;
}
.oracle-section p:last-child { margin-bottom: 0; }
.button-row { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 14px; }
.button {
  min-height: 38px;
  border: 1px solid var(--line-strong);
  background: var(--paper);
  color: var(--ink);
  padding: 9px 12px;
  font: inherit;
  font-size: 13px;
  font-weight: 720;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
.button.primary { background: var(--ink); color: #fff; border-color: var(--ink); }
.button:hover { transform: translateY(-1px); }
.signals {
  display: grid;
  grid-template-columns: repeat(5, minmax(0, 1fr));
  gap: 8px;
  margin-top: 16px;
}
.signal {
  border: 1px solid var(--line);
  background: #faf9f7;
  padding: 10px;
}
.signal strong { display: block; font-size: 20px; line-height: 1; }
.signal span { color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: .04em; }
.excerpt {
  border-left: 3px solid var(--line-strong);
  padding: 8px 0 8px 14px;
  color: var(--muted);
  margin: 10px 0;
}
.method-grid {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 12px;
}
.method-card h3 { margin: 0 0 8px; }
.method-card p { margin: 0; color: var(--muted); }
.footer {
  margin-top: 36px;
  padding: 26px 0 40px;
  border-top: 1px solid var(--line);
  color: var(--muted);
  font-size: 14px;
}
.footer .links { display: flex; gap: 14px; flex-wrap: wrap; margin-top: 10px; }
.detail-layout {
  display: grid;
  grid-template-columns: minmax(0, 1fr) 320px;
  gap: 24px;
  align-items: start;
}
.detail-box {
  border: 1px solid var(--line);
  background: var(--paper);
  padding: 22px;
}
.empty { color: var(--muted); padding: 20px; border: 1px solid var(--line); background: var(--paper); }
@media (max-width: 900px) {
  .hero,
  .detail-layout { grid-template-columns: 1fr; }
  .metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); }
  .company-grid,
  .method-grid { grid-template-columns: 1fr; }
  .report-card { grid-template-columns: 72px minmax(0, 1fr); }
  .report-card .button-row { grid-column: 1 / -1; }
  .signals { grid-template-columns: repeat(2, minmax(0, 1fr)); }
  .topbar .shell { align-items: flex-start; flex-direction: column; padding: 14px 0; }
}
@media (max-width: 560px) {
  .shell { width: min(100% - 22px, 1180px); }
  .metrics { grid-template-columns: 1fr; }
  h1 { font-size: 42px; }
}
"""


SCRIPT = """
function copyText(text) {
  if (navigator.clipboard) {
    navigator.clipboard.writeText(text);
  }
}
document.addEventListener("click", function(event) {
  const btn = event.target.closest("[data-copy]");
  if (!btn) return;
  copyText(btn.getAttribute("data-copy"));
  const old = btn.textContent;
  btn.textContent = "Copied";
  setTimeout(() => { btn.textContent = old; }, 1200);
});
"""


def layout(title: str, body: str, description: str = "", canonical: str = "") -> bytes:
    description = description or "Corporate Cope tracks company earnings, filings and consultancy reports for AI displacement language."
    canonical = canonical or PUBLIC_BASE + "/"
    page = f"""<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{esc(title)}</title>
  <meta name="description" content="{esc(description)}">
  <link rel="canonical" href="{esc(canonical)}">
  <meta property="og:title" content="{esc(title)}">
  <meta property="og:description" content="{esc(description)}">
  <meta property="og:url" content="{esc(canonical)}">
  <meta property="og:type" content="website">
  <style>{CSS}.oracle-float {{
  position: fixed;
  left: max(1rem, env(safe-area-inset-left));
  bottom: max(1rem, env(safe-area-inset-bottom));
  z-index: 9998;
  display: inline-flex;
  flex-direction: column;
  gap: 0.15rem;
  padding: 0.72rem 0.92rem;
  border: 1px solid rgba(255, 255, 255, 0.22);
  border-radius: 0.75rem;
  background: rgba(12, 16, 24, 0.9);
  color: #fff;
  text-decoration: none;
  box-shadow: 0 18px 42px rgba(0, 0, 0, 0.28);
  backdrop-filter: blur(14px);
  -webkit-backdrop-filter: blur(14px);
  transition: transform 160ms ease, box-shadow 160ms ease, border-color 160ms ease;
}}

.oracle-float:hover,
.oracle-float:focus-visible {{
  transform: translateY(-2px);
  border-color: rgba(255, 255, 255, 0.42);
  box-shadow: 0 22px 54px rgba(0, 0, 0, 0.36);
  color: #fff;
}}

.oracle-float-kicker {{
  font-size: 0.64rem;
  font-weight: 700;
  line-height: 1;
  letter-spacing: 0.08em;
  opacity: 0.72;
  text-transform: uppercase;
}}

.oracle-float-title {{
  font-size: 0.95rem;
  font-weight: 800;
  line-height: 1.1;
}}

@media (max-width: 640px) {{
  .oracle-float {{
    left: 0.75rem;
    right: 0.75rem;
    bottom: 0.75rem;
    width: auto;
    align-items: center;
    text-align: center;
  }}

  .oracle-float-kicker {{
    display: none;
  }}
}}
</style>
</head>
<body>
  <header class="topbar">
    <div class="shell">
      <a class="brand" href="/"><span class="mark">CC</span><span>Corporate Cope</span></a>
      <nav>
        <a href="/">Companies</a>
        <a href="/#reports">Reports</a>
        <a href="/feed.json">JSON</a>
        <a href="/llms.txt">llms.txt</a>
        <a href="https://codex.copecheck.com/">Codex</a>
        <a href="https://labs.copecheck.com/">Labs</a>
      </nav>
    </div>
  </header>
  <main>{body}</main>
  <footer class="footer">
    <div class="shell">
      <div>Corporate Cope is a CopeCheck batch archive. It scores public filings and reports against the Discontinuity Thesis.</div>
      <div class="links">
        <a href="https://www.copecheck.com/">Main</a>
        <a href="https://uk.copecheck.com/">UK</a>
        <a href="https://layoffs.copecheck.com/">Layoffs</a>
        <a href="https://capabilities.copecheck.com/">Capabilities</a>
        <a href="https://thesis.copecheck.com/">Thesis</a>
        <a href="https://seo.copecheck.com/">SEO</a>
      </div>
    </div>
  </footer>
  <script>{SCRIPT}</script>
  <a class="oracle-float" href="https://chatgpt.com/g/[redacted]" target="_blank" rel="noopener" aria-label="Ask the Oracle custom GPT">
    <span class="oracle-float-kicker">Custom GPT</span>
    <span class="oracle-float-title">Ask the Oracle</span>
  </a>
</body>
</html>"""
    return page.encode("utf-8")


def report_share(report: dict) -> str:
    if report.get("share_line"):
        return f"{report['company_name']} scores {report['score']}/100 on Corporate Cope: {report['band']}. {report['share_line']} {PUBLIC_BASE}/r/{report['id']}"
    return (
        f"{report['company_name']} scores {report['score']}/100 on Corporate Cope: "
        f"{report['band']}. {report.get('oracle_verdict', '')} {PUBLIC_BASE}/r/{report['id']}"
    )


def render_company_card(company: dict) -> str:
    score = int(round(company.get("average_score") or 0))
    ticker = f" · {company['ticker']}" if company.get("ticker") else ""
    transcript_count = int(company.get("transcript_count") or 0)
    indexed = f"{company.get('report_count', 0)} reports indexed"
    if transcript_count:
        indexed += f" · {transcript_count} transcripts"
    return f"""
<a class="company-card" href="/company/{quote(company['slug'])}">
  <div class="score {score_class(score)}">{score}</div>
  <div>
    <h3>{esc(company['name'])}</h3>
    <div class="meta">{esc(company.get('sector'))}{esc(ticker)}</div>
    <p class="why">{esc(company.get('why_watch'))}</p>
    <div class="meta">{esc(indexed)}</div>
  </div>
</a>"""


def render_report_card(report: dict, compact: bool = False) -> str:
    share = report_share(report)
    score = int(report.get("score") or 0)
    sharp = report.get("killer_line") or report.get("share_line")
    detail = "" if compact else f'<p class="verdict">{esc(sharp or report.get("oracle_verdict"))}</p>'
    return f"""
<article class="report-card">
  <div class="score {score_class(score)}">{score}</div>
  <div>
    <h3><a href="/r/{quote(report['id'])}">{esc(report.get('title'))}</a></h3>
    <div class="meta">{esc(report.get('company_name'))} · {esc(report.get('source_kind'))} · {esc(fmt_date(report.get('filing_date') or report.get('report_date')))}</div>
    {detail}
  </div>
  <div class="button-row">
    <a class="button primary" href="/r/{quote(report['id'])}">Open</a>
    <a class="button" href="{esc(report.get('url'))}" target="_blank" rel="noopener">Source</a>
    <a class="button" href="https://wa.me/?text={quote(share)}" target="_blank" rel="noopener">WhatsApp</a>
    <button class="button" data-copy="{esc(share)}">Copy</button>
  </div>
</article>"""


def render_protocol_scan(scan: dict | None) -> str:
    if not scan:
        return ""
    title = scan.get("title") or ""
    first_line = scan.get("first_line") or ""
    return f"""
<div class="protocol-scan">
  <strong>URL SCAN:</strong>
  <p>{esc(title)}</p>
  <strong style="margin-top:10px;">FIRST LINE:</strong>
  <p>{esc(first_line)}</p>
</div>"""


def render_oracle_sections(sections: list[dict]) -> str:
    if not sections:
        return ""
    rendered = []
    for section in sections:
        title = section.get("title", "Oracle Read")
        paragraphs = section.get("paragraphs") or []
        if isinstance(paragraphs, str):
            paragraphs = [paragraphs]
        rendered.append(
            f"""<section class="oracle-section">
  <h2>{esc(title)}</h2>
  {''.join(f'<p>{esc(paragraph)}</p>' for paragraph in paragraphs)}
</section>"""
        )
    return '<div class="oracle-essay">' + "".join(rendered) + "</div>"


def oracle_spotlight(reports: list[dict]) -> dict | None:
    for report in reports:
        if report.get("id") == "microsoft-fy26-q2-call-transcript":
            return report
    sharp = [report for report in reports if report.get("killer_line") or report.get("share_line")]
    if sharp:
        return sorted(sharp, key=lambda row: row.get("rank_score") or row.get("score") or 0, reverse=True)[0]
    return sorted(reports, key=lambda row: row.get("rank_score") or row.get("score") or 0, reverse=True)[0] if reports else None


def home_page() -> bytes:
    data = load_data()
    companies = sorted(data.get("companies", []), key=lambda row: row.get("average_score") or 0, reverse=True)
    reports = data.get("reports", [])
    latest = sorted(reports, key=lambda row: row.get("filing_date") or row.get("report_date") or "", reverse=True)[:18]
    top = sorted(reports, key=lambda row: row.get("rank_score") or row.get("score") or 0, reverse=True)[:12]
    spotlight = oracle_spotlight(reports)
    spotlight_share = report_share(spotlight) if spotlight else ""
    spotlight_line = (spotlight or {}).get("killer_line") or (spotlight or {}).get("share_line") or ""
    spotlight_section = ""
    if spotlight:
        spotlight_section = f"""
<section class="shell section spotlight">
  <div class="section-head">
    <div>
      <div class="meta">Oracle Cut · {esc(spotlight.get('band'))} · {esc(spotlight.get('score'))}/100</div>
      <h2>{esc(spotlight.get('company_name'))}: {esc(form_label(spotlight))}</h2>
    </div>
    <p>{esc(spotlight.get('title'))}</p>
  </div>
  {f'<div class="oracle-line">{esc(spotlight_line)}</div>' if spotlight_line else ''}
  <p class="verdict">{esc(spotlight.get('oracle_verdict'))}</p>
  <div class="button-row">
    <a class="button primary" href="/r/{quote(spotlight['id'])}">Read the Oracle verdict</a>
    <a class="button" href="/company/{quote(spotlight['company_slug'])}">Company archive</a>
    <a class="button" href="https://wa.me/?text={quote(spotlight_share)}" target="_blank" rel="noopener">WhatsApp</a>
    <button class="button" data-copy="{esc(spotlight_share)}">Copy</button>
  </div>
</section>"""
    generated = data.get("generated_at") or "not yet generated"
    avg_score = round(sum(r["score"] for r in reports) / len(reports), 1) if reports else 0
    transcript_count = sum(1 for r in reports if r.get("form") == "CALL")

    body = f"""
<section class="shell hero">
  <div>
    <h1>Corporate earnings, translated into cope.</h1>
[redacted secret-like line]
  </div>
  <aside class="hero-panel">
    <div class="big">{len(reports)}</div>
    <div class="label">reports currently indexed from {len(companies)} companies and consultancies.</div>
    <div class="button-row">
      <a class="button primary" href="#reports">Read latest</a>
      <a class="button" href="/feed.json">Machine feed</a>
    </div>
  </aside>
</section>
<section class="shell metrics">
  <div class="metric"><strong>{len(companies)}</strong><span>tracked sources</span></div>
  <div class="metric"><strong>{avg_score}</strong><span>average cope score</span></div>
  <div class="metric"><strong>{transcript_count}</strong><span>call transcripts</span></div>
  <div class="metric"><strong>{esc(generated[:10])}</strong><span>last batch run</span></div>
</section>
{spotlight_section}
<section class="shell section">
  <div class="section-head">
    <h2>Watchlist</h2>
    <p>Public companies use official call transcripts where available, then the latest regular SEC filings or official earnings releases. Private consultancies are treated as report-scanner sources.</p>
  </div>
  <div class="company-grid">{''.join(render_company_card(company) for company in companies)}</div>
</section>
<section class="shell section" id="reports">
  <div class="section-head">
    <h2>Latest Reports</h2>
    <p>The archive is designed for batch refreshes around earnings season. Rerun the scanner, review the top rows, publish.</p>
  </div>
  <div class="report-list">{''.join(render_report_card(report, compact=True) for report in latest)}</div>
</section>
<section class="shell section">
  <div class="section-head">
    <h2>Highest Cope</h2>
    <p>These are not claims that the companies are wrong. They are high-signal sources where the labour question is buried hardest under productivity, AI infrastructure and transformation language.</p>
  </div>
  <div class="report-list">{''.join(render_report_card(report) for report in top)}</div>
</section>
<section class="shell section">
  <div class="section-head">
    <h2>Method</h2>
    <p>Cheap first-pass scoring for batch work. Local models can be added later as a second-pass editor, but the site does not need live interaction.</p>
  </div>
  <div class="method-grid">
    <div class="method-card"><h3>Pull</h3><p>Fetch official call transcripts first, then the last two regular public filings or official earnings releases for each tracked company.</p></div>
    <div class="method-card"><h3>Score</h3><p>Measure AI, labour, capex, euphemism and displacement signals with source weighting so transcripts do not get buried under long filings.</p></div>
    <div class="method-card"><h3>Publish</h3><p>Render static public pages, JSON, sitemap and llms.txt. Visitors see finished verdicts, not a spinner.</p></div>
  </div>
</section>"""
    return layout(
        "Corporate Cope - CopeCheck",
        body,
        "Corporate Cope scores earnings, SEC filings and consultancy reports for AI displacement language.",
        PUBLIC_BASE + "/",
    )


def company_page(slug: str) -> bytes:
    data = load_data()
    companies = company_map(data)
    company = companies.get(slug)
    if not company:
        return not_found()
    reports = sorted(reports_for(data, slug), key=lambda row: row.get("filing_date") or row.get("report_date") or "", reverse=True)
    score = int(round(company.get("average_score") or 0))
    body = f"""
<section class="shell hero">
  <div>
    <h1>{esc(company['name'])}</h1>
    <p class="lead">{esc(company.get('why_watch'))}</p>
    <div class="button-row">
      {f'<a class="button" href="{esc(company.get("ir_url"))}" target="_blank" rel="noopener">Investor relations</a>' if company.get("ir_url") else ''}
      <a class="button" href="/">All companies</a>
    </div>
  </div>
  <aside class="hero-panel">
    <div class="big">{score}</div>
    <div class="label">average Corporate Cope score across {len(reports)} indexed reports.</div>
  </aside>
</section>
<section class="shell section">
  <div class="section-head">
    <h2>Reports</h2>
    <p>{esc(company.get('sector'))}</p>
  </div>
  <div class="report-list">{''.join(render_report_card(report) for report in reports) if reports else '<p class="empty">No reports indexed yet.</p>'}</div>
</section>"""
    return layout(
        f"{company['name']} - Corporate Cope",
        body,
        f"{company['name']} Corporate Cope profile: earnings and reports scored for AI displacement language.",
        f"{PUBLIC_BASE}/company/{quote(slug)}",
    )


def report_page(report_id: str) -> bytes:
    data = load_data()
    report = report_by_id(data, report_id)
    if not report:
        return not_found()
    score = int(report.get("score") or 0)
    signals = report.get("signals") or {}
    share = report_share(report)
    excerpts = report.get("excerpts") or []
    takeaways = report.get("oracle_takeaways") or []
    sections = report.get("oracle_sections") or []
    protocol_scan = report.get("protocol_scan") or {}
    killer = report.get("killer_line")
    body = f"""
<section class="shell hero">
  <div>
    <h1>{esc(report.get('company_name'))}: {esc(form_label(report))}</h1>
    <p class="lead">{esc(report.get('oracle_verdict'))}</p>
    {f'<div class="oracle-line">{esc(killer)}</div>' if killer else ''}
    <div class="button-row">
      <a class="button primary" href="{esc(report.get('url'))}" target="_blank" rel="noopener">Read source</a>
      <a class="button" href="/company/{quote(report['company_slug'])}">Company page</a>
      <a class="button" href="https://wa.me/?text={quote(share)}" target="_blank" rel="noopener">WhatsApp</a>
      <button class="button" data-copy="{esc(share)}">Copy verdict</button>
    </div>
  </div>
  <aside class="hero-panel">
    <div class="score {score_class(score)}" style="height:88px;font-size:38px;">{score}</div>
    <div class="label">{esc(report.get('band'))} · {esc(report.get('source_kind'))} · {esc(fmt_date(report.get('filing_date') or report.get('report_date')))}</div>
  </aside>
</section>
<section class="shell section detail-layout">
  <article class="detail-box">
    <h2>{esc(report.get('title'))}</h2>
    <p class="verdict">{esc(report.get('why_watch'))}</p>
    {render_protocol_scan(protocol_scan)}
    {render_oracle_sections(sections)}
    {('<h2 style="margin-top:26px;">Oracle Read</h2><div class="takeaways">' + ''.join(f'<div class="takeaway">{esc(item)}</div>' for item in takeaways) + '</div>') if takeaways else ''}
    <div class="signals">
      <div class="signal"><strong>{signals.get('ai_terms', 0)}</strong><span>AI terms</span></div>
      <div class="signal"><strong>{signals.get('labour_terms', 0)}</strong><span>labour terms</span></div>
      <div class="signal"><strong>{signals.get('capex_terms', 0)}</strong><span>capex terms</span></div>
      <div class="signal"><strong>{signals.get('euphemism_terms', 0)}</strong><span>soft framing</span></div>
      <div class="signal"><strong>{signals.get('direct_displacement_terms', 0)}</strong><span>direct terms</span></div>
    </div>
    <h2 style="margin-top:26px;">Extracts</h2>
    {''.join(f'<p class="excerpt">{esc(excerpt)}</p>' for excerpt in excerpts)}
  </article>
  <aside class="detail-box">
    <h3>Source</h3>
    <p class="verdict">{esc(report.get('source_kind'))}</p>
    <p class="verdict">Filed: {esc(fmt_date(report.get('filing_date')))}<br>Period: {esc(fmt_date(report.get('report_date')))}<br>Words extracted: {esc(report.get('word_count'))}</p>
    <div class="button-row">
      <a class="button primary" href="{esc(report.get('url'))}" target="_blank" rel="noopener">Open source</a>
      <a class="button" href="/">Archive</a>
    </div>
  </aside>
</section>"""
    return layout(
        f"{report.get('company_name')} {report.get('score')}/100 - Corporate Cope",
        body,
        report.get("oracle_verdict", ""),
        f"{PUBLIC_BASE}/r/{quote(report_id)}",
    )


def feed_json() -> bytes:
    data = load_data()
    payload = {
        "site": "Corporate Cope",
        "base_url": PUBLIC_BASE,
        "generated_at": data.get("generated_at"),
        "ai_disclosure": "Scores and Oracle summaries are AI-generated and may contain errors; verify against the linked filing or report.",
        "companies": data.get("companies", []),
        "reports": [
            {
                **report,
                "public_url": f"{PUBLIC_BASE}/r/{report['id']}",
                "company_url": f"{PUBLIC_BASE}/company/{report['company_slug']}",
                "ai_disclosure": "AI-generated analysis; verify against the source report.",
            }
            for report in data.get("reports", [])
        ],
    }
    return json.dumps(payload, ensure_ascii=False, indent=2).encode("utf-8")


def llms_txt() -> bytes:
    data = load_data()
    lines = [
        "# Corporate Cope",
        "",
        "Corporate Cope is a CopeCheck batch archive that scores official call transcripts, public company earnings, SEC filings and consultancy reports for AI displacement language.",
        "",
        f"Base URL: {PUBLIC_BASE}",
        f"Generated at: {data.get('generated_at', '')}",
        "",
        "## Main Feeds",
        f"- JSON feed: {PUBLIC_BASE}/feed.json",
        f"- Sitemap: {PUBLIC_BASE}/sitemap.xml",
        "",
        "## Companies",
    ]
    for company in sorted(data.get("companies", []), key=lambda row: row.get("average_score") or 0, reverse=True):
        lines.append(
            f"- {company['name']}: {company.get('average_score', 0)}/100 across {company.get('report_count', 0)} reports - {PUBLIC_BASE}/company/{company['slug']}"
        )
    lines.extend(["", "## Highest Reports"])
    for report in sorted(data.get("reports", []), key=lambda row: row.get("rank_score") or row.get("score") or 0, reverse=True)[:20]:
        lines.append(f"- {report['company_name']} {report['score']}/100: {report['title']} - {PUBLIC_BASE}/r/{report['id']}")
    return ("\n".join(lines) + "\n").encode("utf-8")


def sitemap_xml() -> bytes:
    data = load_data()
    today = datetime.now(timezone.utc).date().isoformat()
    urls = [PUBLIC_BASE + "/"]
    urls.extend(f"{PUBLIC_BASE}/company/{company['slug']}" for company in data.get("companies", []))
    urls.extend(f"{PUBLIC_BASE}/r/{report['id']}" for report in data.get("reports", []))
    items = "\n".join(f"<url><loc>{esc(url)}</loc><lastmod>{today}</lastmod></url>" for url in urls)
    return f'<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">{items}</urlset>'.encode("utf-8")


def robots_txt() -> bytes:
    return f"User-agent: *\nAllow: /\nSitemap: {PUBLIC_BASE}/sitemap.xml\n".encode("utf-8")


def not_found() -> bytes:
    return layout("Not found - Corporate Cope", '<section class="shell section"><p class="empty">Not found.</p></section>', canonical=PUBLIC_BASE + "/404")


# CopeCheck Network footer, matching the markup used by the Jinja-templated
# sites (careers/eu/policy/quiz). Appended to the injected disclosure footer
# below so every HTML response on this host carries it.
NETWORK_FOOTER = (
    "<p class=\"network-links\" style=\"margin-top:0.8rem;font-size:0.8rem;opacity:0.5;text-align:center;\">CopeCheck Network: <a href=\"https://copecheck.com\" style=\"color:inherit;\">Main</a> &middot; "
    "<a href=\"https://uk.copecheck.com\" style=\"color:inherit;\">UK</a> &middot; "
    "<a href=\"https://countries.copecheck.com\" style=\"color:inherit;\">Countries</a> &middot; "
    "<a href=\"https://eu.copecheck.com\" style=\"color:inherit;\">EU</a> &middot; "
    "<a href=\"https://policy.copecheck.com\" style=\"color:inherit;\">Policy</a> &middot; "
    "<a href=\"https://cities.copecheck.com\" style=\"color:inherit;\">Cities</a> &middot; "
    "<a href=\"https://layoffs.copecheck.com\" style=\"color:inherit;\">Layoffs</a> &middot; "
    "<a href=\"https://careers.copecheck.com\" style=\"color:inherit;\">Careers</a> &middot; "
    "<a href=\"https://quiz.copecheck.com\" style=\"color:inherit;\">Quiz</a> &middot; "
    "<a href=\"https://copecheck.com/contact?from=https://corporate.copecheck.com\" style=\"color:inherit;\">Feedback</a></p>"
)


def ai_disclosure_page() -> bytes:
    return b'''<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>AI Disclosure | Corporate Cope</title></head><body><main><article style="max-width:52rem;margin:3rem auto;line-height:1.65"><h1>How Corporate Cope uses AI</h1><p><strong>Report scores, Oracle verdicts and analytical summaries are generated by artificial intelligence.</strong> Company names, filing metadata and source documents are drawn from public records.</p><h2>Models and method</h2><p>The CopeCheck network uses OpenAI Codex with gpt-5.6-luna at maximum reasoning for the main scoring path and MiniMax models for specialist and fallback pipelines. The corporate batch pipeline extracts labour, AI, capex, euphemism and displacement signals, then applies source weighting and the CopeCheck structural tests.</p><h2>Limits and corrections</h2><p>A score is an interpretation, not a claim that the company or report is false. Models may omit context or infer too much. Verify against the linked filing or report and send corrections to <a href="mailto:btl101@gmail.com?subject=Corporate%20Cope%20correction">btl101@gmail.com</a>.</p></article></main><footer></footer></body></html>'''


def inject_ai_disclosure(body: bytes, content_type: str) -> bytes:
    if not content_type.startswith("text/html"):
        return body
    text = body.decode("utf-8", errors="replace")
    if "cc-ai-label" in text:
        return body
    label = '''<style>.cc-ai-label,.cc-ai-footer{box-sizing:border-box;border:1px solid rgba(245,158,11,.45);border-radius:.65rem;background:rgba(245,158,11,.08);color:inherit;padding:.75rem 1rem;line-height:1.5}.cc-ai-label{margin:1rem auto;max-width:72rem}.cc-ai-label strong{margin-right:.4rem;text-transform:uppercase;letter-spacing:.04em}.cc-ai-label a,.cc-ai-footer a{color:inherit;text-decoration:underline}.cc-ai-footer{margin:1rem 0;font-size:.85rem}</style><aside class="cc-ai-label" role="note"><strong>AI-generated analysis</strong> Scores and Oracle summaries may be generated by AI. <a href="/ai-disclosure">How CopeCheck uses AI</a>.</aside>'''
    footer = '''<p class="cc-ai-footer"><strong>AI disclosure:</strong> Scores and analytical summaries may be AI-generated and may contain errors. <a href="/ai-disclosure">Full disclosure</a>.</p>'''
    main_at = text.find("<main")
    if main_at >= 0:
        main_end = text.find(">", main_at)
        text = text[:main_end + 1] + label + text[main_end + 1:]
    footer += NETWORK_FOOTER
    footer_at = text.find("<footer")
    if footer_at >= 0:
        footer_end = text.find(">", footer_at)
        text = text[:footer_end + 1] + footer + text[footer_end + 1:]
    else:
        text = text.replace("</body>", f"<footer>{footer}</footer></body>", 1)
    return text.encode("utf-8")


class Handler(BaseHTTPRequestHandler):
    def log_message(self, fmt: str, *args: object) -> None:
        return

    def send_bytes(self, body: bytes, content_type: str = "text/html; charset=utf-8", status: int = 200, head_only: bool = False) -> None:
        body = inject_ai_disclosure(body, content_type)
        self.send_response(status)
        self.send_header("Content-Type", content_type)
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Cache-Control", "public, max-age=300")
        self.end_headers()
        if not head_only:
            self.wfile.write(body)

    def handle_read(self, head_only: bool = False) -> None:
        path = urlparse(self.path).path.rstrip("/") or "/"
        if path == "/":
            return self.send_bytes(home_page(), head_only=head_only)
        if path == "/ai-disclosure":
            return self.send_bytes(ai_disclosure_page(), head_only=head_only)
        if path == "/feed.json":
            return self.send_bytes(feed_json(), "application/json; charset=utf-8", head_only=head_only)
        if path == "/llms.txt":
            return self.send_bytes(llms_txt(), "text/plain; charset=utf-8", head_only=head_only)
        if path == "/robots.txt":
            return self.send_bytes(robots_txt(), "text/plain; charset=utf-8", head_only=head_only)
        if path == "/sitemap.xml":
            return self.send_bytes(sitemap_xml(), "application/xml; charset=utf-8", head_only=head_only)
        if path == "/healthz":
            return self.send_bytes(b"ok\n", "text/plain; charset=utf-8", head_only=head_only)
        if path.startswith("/company/"):
            return self.send_bytes(company_page(path.split("/", 2)[2]), head_only=head_only)
        if path.startswith("/r/"):
            return self.send_bytes(report_page(path.split("/", 2)[2]), head_only=head_only)
        return self.send_bytes(not_found(), status=404, head_only=head_only)

    def do_GET(self) -> None:
        self.handle_read(False)

    def do_HEAD(self) -> None:
        self.handle_read(True)


def main() -> None:
    parser = argparse.ArgumentParser(description="Corporate Cope HTTP server")
    parser.add_argument("--host", default="127.0.0.1")
    parser.add_argument("--port", type=int, default=int(os.getenv("PORT", "8109")))
    args = parser.parse_args()
    server = ThreadingHTTPServer((args.host, args.port), Handler)
    print(f"Corporate Cope serving on http://{args.host}:{args.port}")
    server.serve_forever()


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