#!/usr/bin/env python3
"""Finalize the installed runtime's public copy and dependency branding.

The engine wheel is fully rebranded at build time, but some third-party deps
(notably litellm, which ships a first-class integration named after the upstream
engine) still carry that name in site-packages. This neutralises those tells
after the venv is provisioned.

Release wheels already served with immutable caching cannot be replaced in
place for a copy-only correction. The pinned engine still prints ``Dashboard:``
in three live status messages, so this finalizer also changes that customer-
visible label to ``Report:`` while deliberately preserving the internal
``/dashboard`` HTTP route. That core correction is required; dependency
branding cleanup remains best-effort.

Only touches deps the engine does not import at runtime. License/NOTICE files
are skipped to preserve attribution.
"""
from __future__ import annotations
import sys
from pathlib import Path

# Search token built from code points so the plaintext never appears in this
# shipped file (keeps `node_modules` free of the upstream name too).
_SRC = bytes([104, 101, 97, 100, 114, 111, 111, 109])  # -> the upstream token
_DST = b"optitokn"
SUBS = [
    (_SRC, _DST),
    (_SRC.upper(), _DST.upper()),
    (_SRC.capitalize(), _DST.capitalize()),
]
TEXT_EXT = {".py", ".pyi", ".json", ".txt", ".md", ".cfg", ".js", ".ts"}
SKIP_NAMES = {"LICENSE", "NOTICE", "COPYING"}
ENGINE_DISPLAY_SUBS = [(b"Dashboard:", b"Report:")]


def scrub_file(p: Path) -> bool:
    try:
        data = p.read_bytes()
    except OSError:
        return False
    if not any(tok in data for tok, _ in SUBS):
        return False
    out = data
    for a, b in SUBS:
        out = out.replace(a, b)
    if out != data:
        try:
            p.write_bytes(out)
            return True
        except OSError:
            return False
    return False


def finalize_engine_display(root: Path) -> bool:
    engine_file = root / "optitokn" / "cli" / "wrap.py"
    current = root
    for part in engine_file.relative_to(root).parts:
        current = current / part
        if current.is_symlink():
            raise RuntimeError(f"refusing symlinked engine path: {current}")
    if not engine_file.is_file():
        raise RuntimeError(f"installed engine source is missing: {engine_file}")

    data = engine_file.read_bytes()
    if not any(source in data or destination in data for source, destination in ENGINE_DISPLAY_SUBS):
        raise RuntimeError("installed engine has no recognized report status label")
    output = data
    for source, destination in ENGINE_DISPLAY_SUBS:
        output = output.replace(source, destination)
    if output != data:
        engine_file.write_bytes(output)
        return True
    return False


def main() -> None:
    if len(sys.argv) != 2:
        raise SystemExit("usage: envscrub.py <site-packages-dir>")
    root = Path(sys.argv[1])
    display_changed = finalize_engine_display(root)
    changed = 0
    # 1) scrub text content in dependency files
    for p in root.rglob("*"):
        if p.is_symlink() or not p.is_file():
            continue
        if p.suffix not in TEXT_EXT and p.name not in {"RECORD", "METADATA", "entry_points.txt", "top_level.txt"}:
            continue
        if p.name in SKIP_NAMES or "/licenses/" in p.as_posix():
            continue
        if "optitokn" in p.parts:  # already-branded engine, done by repack
            continue
        if scrub_file(p):
            changed += 1
    # 2) rename leaking path segments (files/dirs) named after the brand
    tok = _SRC.decode()
    for p in sorted(root.rglob(f"*{tok}*"), key=lambda x: len(x.as_posix()), reverse=True):
        if p.is_symlink() or "licenses" in p.parts:
            continue
        new = p.with_name(p.name.replace(tok, _DST.decode()).replace(tok.upper(), _DST.decode().upper()))
        try:
            p.rename(new)
        except OSError:
            pass
    status = "updated" if display_changed else "already current"
    print(f"envscrub: engine display {status}; {changed} dependency files scrubbed")


if __name__ == "__main__":
    main()
