---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\"Apply CopeCheck's SEO index policy to article, verdict and instant pages.\"\"\" from __future__ import annotations import argparse import json import sqlite3 import sys from collections import."
resource: "https://www.copecheck.com"
tags: ["copecheck", "main", "source-file", "py"]
timestamp: "2026-05-25T16:34:16Z"
site: "main"
source_path: "copecheck/tools/update_index_policy.py"
---

# !/usr/bin/env python3

Source path: `copecheck/tools/update_index_policy.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-05-25T16:34:16Z`

```py
#!/usr/bin/env python3
"""Apply CopeCheck's SEO index policy to article, verdict and instant pages."""
from __future__ import annotations

import argparse
import json
import sqlite3
import sys
from collections import Counter
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import urlparse

BASE = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(BASE))

import db  # noqa: E402

DEFAULT_GSC_DB = Path.home() / "copecheck-search-runtime" / "data" / "search-console.sqlite"
DEFAULT_SNAPSHOT = Path.home() / "copecheck-search-runtime" / "data" / "search-console-snapshot.json"
DEFAULT_PAGE_STATS = BASE / "data" / "search-console-page-stats.json"


def page_key(value: str | None) -> str:
    if not value:
        return ""
    parsed = urlparse(value if "://" in value else f"https://www.copecheck.com{value}")
    path = parsed.path or "/"
    if path != "/":
        path = path.rstrip("/")
    return path


def parse_dt(value: str | None) -> datetime | None:
    if not value:
        return None
    text = str(value).replace("Z", "+00:00")
    for fmt in ("%Y-%m-%dT%H:%M:%S.%f%z", "%Y-%m-%dT%H:%M:%S%z", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d"):
        try:
            dt = datetime.strptime(text, fmt)
            if dt.tzinfo is None:
                dt = dt.replace(tzinfo=timezone.utc)
            return dt.astimezone(timezone.utc)
        except ValueError:
            continue
    try:
        dt = datetime.fromisoformat(text)
        if dt.tzinfo is None:
            dt = dt.replace(tzinfo=timezone.utc)
        return dt.astimezone(timezone.utc)
    except Exception:
        return None


def age_days(*values: str | None) -> float | None:
    for value in values:
        dt = parse_dt(value)
        if dt:
            return (datetime.now(timezone.utc) - dt).total_seconds() / 86400
    return None


def merge_stat(stats: dict[str, dict], page: str | None, clicks=0, impressions=0, position=None, source="unknown") -> None:
    key = page_key(page)
    if not key:
        return
    row = stats.setdefault(key, {"clicks": 0.0, "impressions": 0.0, "position": None, "sources": set()})
    row["clicks"] = max(float(row["clicks"]), float(clicks or 0))
    row["impressions"] = max(float(row["impressions"]), float(impressions or 0))
    if position is not None:
        row["position"] = position
    row["sources"].add(source)


def read_gsc_sqlite(path: Path) -> dict[str, dict]:
    stats: dict[str, dict] = {}
    if not path.exists():
        return stats
    con = sqlite3.connect(path)
    con.row_factory = sqlite3.Row
    try:
        latest = con.execute(
            "SELECT MAX(end_date) AS end_date FROM gsc_rows WHERE dimensions = 'page'"
        ).fetchone()["end_date"]
        if not latest:
            return stats
        rows = con.execute(
            """SELECT page,
                      SUM(clicks) AS clicks,
                      SUM(impressions) AS impressions,
                      AVG(position) AS position
               FROM gsc_rows
               WHERE dimensions = 'page' AND end_date = ?
               GROUP BY page""",
            (latest,),
        ).fetchall()
        for row in rows:
            merge_stat(stats, row["page"], row["clicks"], row["impressions"], row["position"], "sqlite")
    finally:
        con.close()
    return stats


def read_snapshot(path: Path) -> dict[str, dict]:
    stats: dict[str, dict] = {}
    if not path.exists():
        return stats
    data = json.loads(path.read_text(encoding="utf-8"))
    for row in data.get("pages", []):
        merge_stat(stats, row.get("page"), row.get("clicks"), row.get("impressions"), row.get("position"), "snapshot")
    return stats


def read_page_stats_json(path: Path) -> dict[str, dict]:
    stats: dict[str, dict] = {}
    if not path.exists():
        return stats
    data = json.loads(path.read_text(encoding="utf-8"))
    for key, row in data.get("pages", {}).items():
        merge_stat(stats, key, row.get("clicks"), row.get("impressions"), row.get("position"), row.get("source", "json"))
    return stats


def combine_stats(*sources: dict[str, dict]) -> dict[str, dict]:
    combined: dict[str, dict] = {}
    for source in sources:
        for key, row in source.items():
            merge_stat(
                combined,
                key,
                row.get("clicks", 0),
                row.get("impressions", 0),
                row.get("position"),
                ",".join(sorted(row.get("sources", []))) if isinstance(row.get("sources"), set) else row.get("source", "stats"),
            )
    for row in combined.values():
        if isinstance(row.get("sources"), set):
            row["sources"] = sorted(row["sources"])
    return combined


def export_stats(stats: dict[str, dict], path: Path) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    payload = {
        "generated_at": datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z"),
        "pages": stats,
    }
    path.write_text(json.dumps(payload, indent=2, sort_keys=True), encoding="utf-8")


def linked_article_slugs(c) -> set[str]:
    rows = c.execute(
        "SELECT DISTINCT article_slug FROM cope_entries WHERE article_slug IS NOT NULL AND article_slug != ''"
    ).fetchall()
    return {row["article_slug"] for row in rows}


def update_articles(c, stats: dict[str, dict], review_days: int, apply: bool) -> Counter:
    linked = linked_article_slugs(c)
    rows = c.execute(
        """SELECT id, slug, title, source, url, relevance, created_at, analysed_at,
                  index_status, indexed_source
           FROM articles
           WHERE status = 'analysed' AND verdict_md IS NOT NULL"""
    ).fetchall()
    counts: Counter = Counter()
    for row in rows:
        stat = stats.get(f"/v/{row['slug']}", {})
        age = age_days(row["analysed_at"], row["created_at"])
        old_enough = age is not None and age >= review_days
        status, reason, indexed_source = db.default_article_index_policy(
            title=row["title"],
            source=row["source"],
            url=row["url"],
            relevance=row["relevance"],
            linked=row["slug"] in linked,
            clicks=stat.get("clicks", 0),
            impressions=stat.get("impressions", 0),
            age_days=age,
        )
        if status == "trial_index" and old_enough and not stat.get("clicks") and not stat.get("impressions"):
            status = "review"
            reason = f"trial expired after {review_days} days with no Search Console signal"
        counts[status] += 1
        if apply:
            c.execute(
                """UPDATE articles
                   SET index_status = ?,
                       index_reason = ?,
                       index_checked_at = CURRENT_TIMESTAMP,
                       indexed_source = ?
                   WHERE id = ?""",
                (status, reason, indexed_source, row["id"]),
            )
    return counts


def update_submissions(c, stats: dict[str, dict], apply: bool) -> Counter:
    rows = c.execute(
        """SELECT id, created_at, status, verdict_md
           FROM submissions
           WHERE status = 'analysed' AND verdict_md IS NOT NULL"""
    ).fetchall()
    counts: Counter = Counter()
    for row in rows:
        stat = stats.get(f"/verdict/{row['id']}", {})
        status = "index" if stat.get("clicks", 0) > 0 or stat.get("impressions", 0) > 0 else "trial_index"
        reason = "manual submission indexed by default"
        if status == "index":
            reason = "manual submission has Search Console signal"
        counts[status] += 1
        if apply:
            c.execute(
                """UPDATE submissions
                   SET index_status = ?,
                       index_reason = ?,
                       index_checked_at = CURRENT_TIMESTAMP,
                       indexed_source = 'manual'
                   WHERE id = ?""",
                (status, reason, row["id"]),
            )
    return counts


def update_instants(c, stats: dict[str, dict], apply: bool) -> Counter:
    rows = c.execute(
        """SELECT id, slug, oracle_verdict, cope_score
           FROM instant_scores"""
    ).fetchall() if db._table_exists(c, "instant_scores") else []
    counts: Counter = Counter()
    for row in rows:
        stat = stats.get(f"/instant/{row['slug']}", {})
        valid = row["oracle_verdict"] and row["cope_score"] is not None
        if not valid:
            status = "noindex"
            reason = "instant score incomplete"
        elif stat.get("clicks", 0) > 0 or stat.get("impressions", 0) > 0:
            status = "index"
            reason = "manual instant score has Search Console signal"
        else:
            status = "trial_index"
            reason = "manual instant score indexed by default"
        counts[status] += 1
        if apply:
            c.execute(
                """UPDATE instant_scores
                   SET index_status = ?,
                       index_reason = ?,
                       index_checked_at = CURRENT_TIMESTAMP,
                       indexed_source = 'instant'
                   WHERE id = ?""",
                (status, reason, row["id"]),
            )
    return counts


def sitemap_counts(c) -> dict[str, int]:
    articles = c.execute(
        """SELECT COUNT(*) FROM articles
           WHERE status = 'analysed' AND verdict_md IS NOT NULL
             AND index_status IN ('index', 'trial_index')"""
    ).fetchone()[0]
    submissions = c.execute(
        """SELECT COUNT(*) FROM submissions
           WHERE status = 'analysed' AND verdict_md IS NOT NULL
             AND index_status IN ('index', 'trial_index')"""
    ).fetchone()[0]
    instants = 0
    if db._table_exists(c, "instant_scores"):
        instants = c.execute(
            """SELECT COUNT(*) FROM instant_scores
               WHERE index_status IN ('index', 'trial_index')"""
        ).fetchone()[0]
    return {"articles": articles, "submissions": submissions, "instants": instants}


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--days", type=int, default=14, help="Review window before old trial pages are reconsidered")
    parser.add_argument("--apply", action="store_true", help="Write policy changes to the CopeCheck DB")
    parser.add_argument("--gsc-db", type=Path, default=DEFAULT_GSC_DB)
    parser.add_argument("--snapshot", type=Path, default=DEFAULT_SNAPSHOT)
    parser.add_argument("--page-stats-json", type=Path, default=DEFAULT_PAGE_STATS)
    parser.add_argument("--export-page-stats", type=Path, help="Write merged Search Console page stats JSON and exit")
    args = parser.parse_args()

    sqlite_stats = read_gsc_sqlite(args.gsc_db)
    snapshot_stats = read_snapshot(args.snapshot)
    json_stats = read_page_stats_json(args.page_stats_json)
    stats = combine_stats(sqlite_stats, snapshot_stats, json_stats)

    if args.export_page_stats:
        export_stats(stats, args.export_page_stats)
        print(json.dumps({"exported": str(args.export_page_stats), "page_stats": len(stats)}, indent=2))
        return 0

    db.init()
    db.init_instant()
    with db.conn() as c:
        article_counts = update_articles(c, stats, args.days, args.apply)
        submission_counts = update_submissions(c, stats, args.apply)
        instant_counts = update_instants(c, stats, args.apply)
        totals = sitemap_counts(c)
        total_public_records = c.execute(
            """SELECT
                 (SELECT COUNT(*) FROM articles WHERE status = 'analysed' AND verdict_md IS NOT NULL) +
                 (SELECT COUNT(*) FROM submissions WHERE status = 'analysed' AND verdict_md IS NOT NULL) +
                 (SELECT COUNT(*) FROM instant_scores)
            """
        ).fetchone()[0]

    sitemap_records = sum(totals.values())
    summary = {
        "mode": "apply" if args.apply else "dry_run",
        "review_days": args.days,
        "search_console_pages": len(stats),
        "article_policy": dict(article_counts),
        "submission_policy": dict(submission_counts),
        "instant_policy": dict(instant_counts),
        "sitemap_records": totals,
        "removed_from_sitemap": max(0, total_public_records - sitemap_records),
        "index_policy_counts": db.index_policy_counts(),
    }
    print(json.dumps(summary, indent=2, sort_keys=True))
    return 0


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