#!/usr/bin/env python3
# ZEUS-SELFCHECK-RULES (marker: the scanner skips any file that carries this line, so it never reports itself)
"""Standalone copy for openai-2026-12-11.
Zeus deadline self-check (DRAFT, v0.1, rules last verified 2026-11-21).

Finds lines in a local folder that reference platform features with an announced vendor cutoff
(model IDs, endpoints, SDK calls, connection strings). Prints file:line and the vendor-named
replacement. Exit code 0 = nothing found, 1 = findings, 2 = usage error.

Safety: Python 3 standard library only. It only READS text files. It never imports, runs or
evaluates the files it scans, makes no network connections and sends nothing anywhere.
It skips .git, node_modules, virtualenvs, symlinks, binary files and files over --max-bytes.

Usage:
  python3 zeus_selfcheck.py [--cutoff NAME | --rules FILE ...] [options] [FOLDER]
  python3 check-openai-2027-01-14.py ~/code/my-app        (standalone copy, rules built in)

This is a free first look, not an audit: it can miss calls built at runtime (for example a model
name read from a database or glued together from parts) and it can flag text that is not a live call.
"""
import argparse
import datetime
import json
import os
import re
import sys

VERSION = "0.1.0"
# Rules for openai-2026-12-11 (vendor notice: https://developers.openai.com/api/docs/deprecations; checked 2026-11-21)
EMBEDDED_RULES = [json.loads(r"""
{
 "cutoff": "openai-2026-12-11",
 "date": "2026-12-11",
 "date_status": "verified",
 "grep": "(^|[^A-Za-z0-9._-])(gpt-5(-mini|-nano|-pro)?|o3(-pro)?)(-20[0-9]{2}-[0-9]{2}-[0-9]{2})?([^A-Za-z0-9._-]|$)|gpt-5-chat-latest|gpt-5-codex",
 "notice_url": "https://developers.openai.com/api/docs/deprecations",
 "rules": [
  {
   "date": "2026-12-11",
   "id": "OAI1211-GPT5",
   "ids": [
    "gpt-5",
    "gpt-5-2025-08-07"
   ],
   "kind": "model",
   "replacement": "gpt-6.1-sol",
   "what": "gpt-5 model ID"
  },
  {
   "date": "2026-12-11",
   "id": "OAI1211-GPT5-MINI",
   "ids": [
    "gpt-5-mini",
    "gpt-5-mini-2025-08-07"
   ],
   "kind": "model",
   "replacement": "gpt-6.1-terra",
   "what": "gpt-5-mini model ID"
  },
  {
   "date": "2026-12-11",
   "id": "OAI1211-GPT5-NANO",
   "ids": [
    "gpt-5-nano",
    "gpt-5-nano-2025-08-07"
   ],
   "kind": "model",
   "replacement": "gpt-6-luna",
   "what": "gpt-5-nano model ID"
  },
  {
   "date": "2026-12-11",
   "id": "OAI1211-GPT5-PRO",
   "ids": [
    "gpt-5-pro",
    "gpt-5-pro-2025-10-06"
   ],
   "kind": "model",
   "replacement": "gpt-6.1-sol with reasoning.mode: pro (Responses API)",
   "what": "gpt-5-pro model ID"
  },
  {
   "date": "2026-12-11",
   "id": "OAI1211-O3",
   "ids": [
    "o3",
    "o3-2025-04-16"
   ],
   "kind": "model",
   "replacement": "gpt-6.1-sol",
   "what": "o3 model ID"
  },
  {
   "date": "2026-12-11",
   "id": "OAI1211-O3-PRO",
   "ids": [
    "o3-pro",
    "o3-pro-2025-06-10"
   ],
   "kind": "model",
   "replacement": "gpt-6.1-sol with reasoning.mode: pro (Responses API)",
   "what": "o3-pro model ID"
  },
  {
   "date": "2026-07-23",
   "id": "OAI1211-RETIRED-JUL",
   "ids": [
    "gpt-5-chat-latest",
    "gpt-5-codex"
   ],
   "kind": "model",
   "replacement": "gpt-5.6-sol",
   "what": "gpt-5 alias already shut down"
  }
 ],
 "title": "OpenAI gpt-5 family, o3 and o3-pro shutdown",
 "vendor": "OpenAI",
 "verified": "2026-11-21"
}
""")]

MARKER = "ZEUS-SELFCHECK-RULES"
SKIP_DIRS = {
    ".git", ".hg", ".svn", "node_modules", "bower_components", ".venv", "venv", "__pycache__",
    "site-packages", ".tox", ".nox", ".mypy_cache", ".pytest_cache", ".ruff_cache", ".next", ".nuxt",
    ".svelte-kit", ".turbo", ".cache", ".parcel-cache", "coverage", ".idea", ".vscode", ".terraform",
}
BINARY_EXT = {
    ".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico", ".bmp", ".tif", ".tiff", ".pdf", ".zip", ".gz",
    ".tgz", ".bz2", ".xz", ".7z", ".rar", ".jar", ".war", ".class", ".pyc", ".pyo", ".so", ".dll",
    ".dylib", ".exe", ".bin", ".o", ".a", ".wasm", ".woff", ".woff2", ".ttf", ".otf", ".eot", ".mp3",
    ".mp4", ".mov", ".avi", ".wav", ".flac", ".ogg", ".webm", ".sqlite", ".db", ".parquet", ".npy",
    ".pkl", ".pt", ".onnx", ".safetensors", ".psd", ".ai", ".sketch",
}
DOC_EXT = {".md", ".markdown", ".rst", ".adoc", ".txt"}
HASH_EXT = {".py", ".sh", ".bash", ".zsh", ".fish", ".rb", ".yml", ".yaml", ".toml", ".env", ".ini",
            ".cfg", ".conf", ".r", ".pl", ".ps1", ".tf", ".properties", ".dockerfile"}
SLASH_EXT = {".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".java", ".go", ".rs", ".c", ".h", ".cc",
             ".cpp", ".hpp", ".cs", ".kt", ".kts", ".swift", ".php", ".scala", ".dart", ".jsonc",
             ".json5", ".groovy", ".prisma"}
DASH_EXT = {".sql", ".lua", ".hs"}
TAG_EXT = {".html", ".htm", ".xml", ".vue", ".svelte", ".astro"}
DEFAULT_MAX_BYTES = 2000000
SNIPPET = 160


CONFIG_EXT = {".env", ".yml", ".yaml", ".toml", ".ini", ".cfg", ".conf", ".properties", ".sh", ".bash",
              ".zsh", ".dockerfile"}


def is_config(path):
    name = os.path.basename(path).lower()
    ext = os.path.splitext(name)[1]
    return ext in CONFIG_EXT or name.startswith(".env") or name in ("dockerfile", "procfile") or (ext == "" and "." not in name.lstrip("."))


def comment_prefixes(path):
    name = os.path.basename(path).lower()
    ext = os.path.splitext(name)[1]
    if name in ("dockerfile", "makefile", "procfile", "gemfile") or name.startswith(".env"):
        return ("#",)
    if ext in HASH_EXT:
        return ("#",)
    if ext in SLASH_EXT:
        return ("//", "/*", "*")
    if ext in DASH_EXT:
        return ("--", "/*", "*")
    if ext in TAG_EXT:
        return ("<!--", "//", "/*", "*")
    return ("#", "//")


def model_patterns(ids, id_regex=None):
    """Compile the contexts in which a model ID counts as used: a quoted string (optionally with a
    provider/path prefix or ft: fine-tune wrapper), a /models/<id> URL path or a --model flag.
    Second list, used only in config-style files (.env, YAML, TOML, INI, shell, Dockerfile): an
    unquoted value (KEY=id, key: id) or a YAML list item. Keeping those out of code files avoids
    flagging a variable that happens to be named like a model (e.g. o3 = ...)."""
    alts = [re.escape(i) for i in sorted(ids or [], key=len, reverse=True)]
    if id_regex:
        alts.insert(0, "(?:%s)" % id_regex)
    mid = "(%s)" % "|".join(alts)
    q = "[\"'`]"
    return [
        re.compile(r"(?<=%s)(?:ft:)?(?:[\w.@-]+/)*%s(?=(?::[^\"'`\s]*)?%s)" % (q, mid, q)),
        re.compile(r"(?<=/models/)%s(?=[:/?#\s\"'`]|$)" % mid),
        re.compile(r"(?<=--model[= ])%s(?=[\s\"'`]|$)" % mid),
    ], [
        re.compile(r"^\s*(?:(?:export|ENV|ARG)\s+)?[A-Za-z_][\w.-]*\s*[:=]\s*%s(?=\s*(?:#.*)?$)" % mid),
        re.compile(r"^\s*-\s+%s(?=\s*(?:#.*)?$)" % mid),
    ]


class Rule(object):
    def __init__(self, d, cutoff):
        self.id = d["id"]
        self.cutoff = cutoff
        self.kind = d.get("kind", "model")
        self.date = d.get("date", "")
        self.what = d.get("what", "")
        self.replacement = d.get("replacement", "")
        self.status = d.get("status", "deprecated")  # deprecated | check
        self.note = d.get("note", "")
        self.config_patterns = []
        if self.kind == "model":
            self.patterns, self.config_patterns = model_patterns(d.get("ids"), d.get("id_regex"))
        elif self.kind == "regex":
            flags = re.IGNORECASE if "i" in d.get("flags", "") else 0
            pats = d["pattern"] if isinstance(d["pattern"], list) else [d["pattern"]]
            self.patterns = [re.compile(p, flags) for p in pats]
        else:
            raise ValueError("unknown rule kind: %s" % self.kind)

    def find(self, line, config=False):
        out = []
        for p in self.patterns + (self.config_patterns if config else []):
            for m in p.finditer(line):
                g = m.group(1) if m.groups() and m.group(1) else m.group(0)
                start = m.start(1) if m.groups() and m.group(1) else m.start(0)
                out.append((start, g))
        return out


def load_rule_sets(paths=None, cutoff=None, embedded=None):
    sets = []
    if embedded is not None:
        sets = list(embedded)
    else:
        here = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rules")
        files = list(paths or [])
        if cutoff:
            files.append(os.path.join(here, cutoff + ".json"))
        if not files:
            files = sorted(os.path.join(here, f) for f in os.listdir(here) if f.endswith(".json"))
        for f in files:
            with open(f, "r", encoding="utf-8") as fh:
                sets.append(json.load(fh))
    rules = []
    for s in sets:
        for d in s["rules"]:
            rules.append(Rule(d, s["cutoff"]))
    return sets, rules


def iter_files(root, include_docs=False, max_bytes=DEFAULT_MAX_BYTES, skipped=None):
    skipped = skipped if skipped is not None else {}

    def skip(reason):
        skipped[reason] = skipped.get(reason, 0) + 1

    if os.path.isfile(root):
        yield root
        return
    for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
        keep = []
        for d in sorted(dirnames):
            full = os.path.join(dirpath, d)
            if d in SKIP_DIRS or os.path.islink(full):
                skip("skipped folder")
                continue
            try:
                if os.path.exists(os.path.join(full, "pyvenv.cfg")):
                    skip("skipped folder")
                    continue
            except OSError:
                pass
            keep.append(d)
        dirnames[:] = keep
        for f in sorted(filenames):
            full = os.path.join(dirpath, f)
            ext = os.path.splitext(f)[1].lower()
            if os.path.islink(full):
                skip("symlink")
                continue
            if ext in BINARY_EXT:
                skip("binary")
                continue
            if ext in DOC_EXT and not include_docs:
                skip("docs (use --include-docs)")
                continue
            try:
                if os.path.getsize(full) > max_bytes:
                    skip("too large")
                    continue
            except OSError:
                skip("unreadable")
                continue
            yield full


def read_text(path):
    try:
        with open(path, "rb") as fh:
            data = fh.read()
    except OSError:
        return None, "unreadable"
    if b"\x00" in data[:8192]:
        return None, "binary"
    if MARKER.encode() in data[:4096]:
        return None, "self-check file"
    return data.decode("utf-8", errors="replace"), None


def scan(root, rules, include_docs=False, max_bytes=DEFAULT_MAX_BYTES):
    findings = []
    skipped = {}
    scanned = 0
    base = root if os.path.isdir(root) else os.path.dirname(root) or "."
    for path in iter_files(root, include_docs, max_bytes, skipped):
        text, why = read_text(path)
        if text is None:
            skipped[why] = skipped.get(why, 0) + 1
            continue
        scanned += 1
        prefixes = comment_prefixes(path)
        config = is_config(path)
        rel = os.path.relpath(path, base).replace(os.sep, "/")
        for n, line in enumerate(text.splitlines(), 1):
            stripped = line.lstrip()
            in_comment = any(stripped.startswith(p) for p in prefixes)
            seen = set()
            for r in rules:
                for start, match in r.find(line, config):
                    key = (start, match)
                    if key in seen:
                        continue
                    seen.add(key)
                    lo = max(0, start - 60)
                    snippet = line[lo:lo + SNIPPET].strip()
                    findings.append({
                        "file": rel, "line": n, "col": start + 1, "match": match, "rule": r.id,
                        "cutoff": r.cutoff, "date": r.date, "what": r.what, "replacement": r.replacement,
                        "status": r.status, "note": r.note, "comment": in_comment, "snippet": snippet,
                    })
    findings.sort(key=lambda f: (f["file"], f["line"], f["col"], f["rule"]))
    return findings, scanned, skipped


def when_text(date, today):
    try:
        d = datetime.date(*[int(x) for x in date.split("-")])
    except (ValueError, AttributeError, TypeError):
        return date or "date not set"
    days = (d - today).days
    if days < 0:
        return "date passed on %s: already retired per the vendor notice" % date
    if days == 0:
        return "cutoff is today (%s)" % date
    return "cutoff %s (%d days)" % (date, days)


def main(argv=None):
    ap = argparse.ArgumentParser(description="Zeus deadline self-check (offline, read-only).")
    ap.add_argument("folder", nargs="?", default=".", help="folder (or file) to scan, default: current folder")
    ap.add_argument("--cutoff", help="rule set name from the rules/ folder, e.g. openai-2027-01-14")
    ap.add_argument("--rules", action="append", help="path to a rules JSON file (repeatable)")
    ap.add_argument("--list", action="store_true", help="list the rule sets and rules, then exit")
    ap.add_argument("--include-docs", action="store_true", help="also scan .md/.rst/.txt files")
    ap.add_argument("--strict", action="store_true", help="count matches on comment lines in the exit code")
    ap.add_argument("--max-bytes", type=int, default=DEFAULT_MAX_BYTES, help="skip files larger than this")
    ap.add_argument("--json", action="store_true", help="print findings as JSON")
    ap.add_argument("--today", help="YYYY-MM-DD, for the days-left text (default: your computer's date)")
    a = ap.parse_args(argv)
    try:
        sets, rules = load_rule_sets(a.rules, a.cutoff, EMBEDDED_RULES)
    except (OSError, ValueError, KeyError) as e:
        print("error: could not load rules: %s" % e, file=sys.stderr)
        return 2
    today = datetime.date.today()
    if a.today:
        try:
            today = datetime.date(*[int(x) for x in a.today.split("-")])
        except ValueError:
            print("error: --today must be YYYY-MM-DD", file=sys.stderr)
            return 2
    if a.list:
        for s in sets:
            print("%s: %s [date %s, %s; checked %s]" % (s["cutoff"], s["title"], s["date"], s.get("date_status", ""), s["verified"]))
            print("  vendor notice: %s" % s["notice_url"])
            for r in s["rules"]:
                print("  - %s: %s -> %s" % (r["id"], r.get("what", ""), r.get("replacement", "")))
        return 0
    if not os.path.exists(a.folder):
        print("error: no such folder: %s" % a.folder, file=sys.stderr)
        return 2
    findings, scanned, skipped = scan(a.folder, rules, a.include_docs, a.max_bytes)
    live = [f for f in findings if a.strict or not f["comment"]]
    if a.json:
        print(json.dumps({"version": VERSION, "rule_sets": [s["cutoff"] for s in sets], "files_scanned": scanned,
                          "skipped": skipped, "live_findings": len(live), "findings": findings}, indent=2))
        return 1 if live else 0
    for s in sets:
        flag = "" if s.get("date_status") == "verified" else "  (DATE UNVERIFIED: see the vendor notice)"
        print("# %s: %s, date %s%s" % (s["cutoff"], s["title"], s["date"], flag))
    for f in findings:
        tag = "NOTE (comment)" if f["comment"] and not a.strict else ("CHECK" if f["status"] == "check" else "HIT")
        print("%s:%d: %s [%s] '%s': %s. Suggested: %s. %s." % (
            f["file"], f["line"], tag, f["rule"], f["match"], f["what"], f["replacement"], when_text(f["date"], today)))
        if f["note"]:
            print("    note: %s" % f["note"])
    sk = ", ".join("%s %d" % (k, v) for k, v in sorted(skipped.items())) or "none"
    print("\n%d file(s) scanned; %d finding(s), %d counted (comments are notes unless --strict); skipped: %s"
          % (scanned, len(findings), len(live), sk))
    if live:
        print("Result: affected references found (exit 1). This is a first look, not an audit.")
        return 1
    print("Result: nothing found by these patterns (exit 0). Names built at runtime are not visible to this check.")
    return 0


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