#!/usr/bin/env python3
"""
Refresh a script's hash in scheduled-tasks.json baseline.
Tony calls this after confirming a legitimate script update.

Usage:
  python3 refresh-baseline.py <script-path>
  python3 refresh-baseline.py --all   (refresh all existing scripts)

Steve never calls this automatically. Tony must confirm intentional changes.
"""

import sys, os, json, hashlib
from datetime import datetime

BASELINE_FILE = "/Users/tonyclaw/.openclaw/workspace/agents/security-steve/scheduled-tasks.json"

def hash_file(path):
    return hashlib.sha256(open(path, "rb").read()).hexdigest()[:20]

def refresh(script_path):
    data = json.load(open(BASELINE_FILE))
    baseline = data.get("scripts", {})

    # Normalize path
    expanded = os.path.expanduser(script_path)
    
    # Find matching key (handle both ~ and full path)
    matched_key = None
    for key in baseline:
        if os.path.expanduser(key) == expanded:
            matched_key = key
            break

    if not matched_key:
        # New script — add it
        matched_key = script_path if "~" in script_path else script_path
        print(f"Adding new entry: {matched_key}")

    if not os.path.exists(expanded):
        print(f"ERROR: File not found: {expanded}")
        sys.exit(1)

    old_hash = baseline.get(matched_key, {}).get("hash", "none")
    new_hash = hash_file(expanded)
    size = os.path.getsize(expanded)

    baseline[matched_key] = {
        "hash": new_hash,
        "size_bytes": size,
        "baselined": datetime.now().strftime("%Y-%m-%d"),
        "exists": True,
        "last_refreshed": datetime.now().isoformat(),
        "refreshed_by": "Tony (manual confirmation)"
    }

    data["scripts"] = baseline
    data["last_updated"] = datetime.now().isoformat()
    json.dump(data, open(BASELINE_FILE, "w"), indent=2)

    print(f"✅ Refreshed: {matched_key}")
    print(f"   Hash: {old_hash} → {new_hash}")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(__doc__)
        sys.exit(1)

    if sys.argv[1] == "--all":
        data = json.load(open(BASELINE_FILE))
        count = 0
        for key, meta in data["scripts"].items():
            expanded = os.path.expanduser(key)
            if os.path.exists(expanded):
                new_hash = hash_file(expanded)
                meta["hash"] = new_hash
                meta["size_bytes"] = os.path.getsize(expanded)
                meta["exists"] = True
                meta["last_refreshed"] = datetime.now().isoformat()
                count += 1
        data["last_updated"] = datetime.now().isoformat()
        json.dump(data, open(BASELINE_FILE, "w"), indent=2)
        print(f"✅ Refreshed all: {count} scripts updated")
    else:
        refresh(sys.argv[1])
