#!/usr/bin/env python3
# CHECK -- sol-profile-file-class-re (2026-10-31).
#
# Verdict = exit code. Exit 0 iff an INDEPENDENT recompute straight from the
# live sol profile matches the committed JSON artifact (tier counts AND row
# count) and the committed MD tier table.
#
# Recompute rules (must match the generator):
#   ARTIFACT: relpath under a lock/DB/cache/backup dir, or extension in
#             .db .sqlite .sqlite3 .sqlite3-journal .lock .pyc .pyo .bak
#             .orig .tmp .part .gz .tgz .zip .dump .log.
#   ACTIVE:   regular file with mtime within the last 45 days.
#   STALE:    regular file with mtime older than 45 days.
import os
import json
import datetime
import sys

ROOT = "/root/.hermes/profiles/sol"
REPO = "/root/troupe-standup"
ARTIFACT_DIRS = {"audio_cache", "image_cache", "cache", "__pycache__", "backups", "bin", "hooks",
                 "keys", ".pytest_cache", ".ruff_cache", ".mypy_cache", ".tox", "node_modules"}
ARTIFACT_EXTS = {".db", ".sqlite", ".sqlite3", ".sqlite3-journal", ".lock", ".pyc", ".pyo", ".bak",
                 ".orig", ".tmp", ".part", ".gz", ".tgz", ".zip", ".dump", ".log"}
JSON_PATH = os.path.join(REPO, "wizard-work", "sol", "sol-profile-file-class-2026-10-31.json")
MD_PATH = os.path.join(REPO, "wizard-work", "sol", "sol-profile-file-class-2026-10-31.md")


def classify(rel):
    if any(rel.startswith(ad + os.sep) for ad in ARTIFACT_DIRS):
        return "ARTIFACT"
    ext = os.path.splitext(rel)[1].lower()
    if ext in ARTIFACT_EXTS:
        return "ARTIFACT"
    st = os.stat(os.path.join(ROOT, rel))
    days = (datetime.datetime.now(datetime.timezone.utc) -
            datetime.datetime.fromtimestamp(st.st_mtime, datetime.timezone.utc)).total_seconds() / 86400.0
    return "ACTIVE" if days <= 45 else "STALE"


def recompute():
    counts = {"ACTIVE": 0, "STALE": 0, "ARTIFACT": 0}
    n = 0
    for dirpath, dirnames, filenames in os.walk(ROOT):
        for fn in filenames:
            p = os.path.join(dirpath, fn)
            rel = os.path.relpath(p, ROOT)
            counts[classify(rel)] += 1
            n += 1
    return counts, n


def main():
    live_counts, live_n = recompute()

    with open(JSON_PATH) as f:
        records = json.load(f)
    json_counts = {"ACTIVE": 0, "STALE": 0, "ARTIFACT": 0}
    for _, t in records:
        json_counts[t] += 1

    print("OK: recompute      ACTIVE=%d STALE=%d ARTIFACT=%d files=%d" % (
        live_counts["ACTIVE"], live_counts["STALE"], live_counts["ARTIFACT"], live_n))
    print("OK: committed JSON ACTIVE=%d STALE=%d ARTIFACT=%d rows=%d" % (
        json_counts["ACTIVE"], json_counts["STALE"], json_counts["ARTIFACT"], len(records)))

    failures = []
    if live_counts != json_counts:
        failures.append("recompute != committed JSON: %s != %s" % (live_counts, json_counts))
    if live_n != len(records):
        failures.append("live file count %d != JSON rows %d" % (live_n, len(records)))

    md = ""
    try:
        md = open(MD_PATH).read()
    except OSError:
        md = ""
    for tier in ("ACTIVE", "STALE", "ARTIFACT"):
        m = None
        for line in md.splitlines():
            if line.startswith("|") and tier in line:
                parts = [p.strip() for p in line.strip("|").split("|")]
                if len(parts) >= 2 and parts[0] == tier:
                    m = parts[1]
        if m is None or int(m) != live_counts[tier]:
            failures.append("MD %s count %r != %d" % (tier, m, live_counts[tier]))

    if failures:
        print("FAIL: " + "; ".join(failures), file=sys.stderr)
        sys.exit(1)

    print("PASS: sol-profile file triage verified (ACTIVE=%d STALE=%d ARTIFACT=%d files=%d)" % (
        live_counts["ACTIVE"], live_counts["STALE"], live_counts["ARTIFACT"], live_n))
    sys.exit(0)


if __name__ == "__main__":
    main()
