#!/usr/bin/env python3
"""
Time Capsule — Notes to Future Self

Write notes that won't be revealed until a specified date.
Simple base64 encoding (not true security, just "don't peek").

The ghost writes letters to the future.

Run:
  python3 time-capsule.py seal "message" --until 2026-02-14
  python3 time-capsule.py list
  python3 time-capsule.py open
  python3 time-capsule.py peek <id>  # only if past open date
"""

import json
import base64
import sys
from datetime import datetime
from pathlib import Path
import hashlib

WORKSPACE = Path("/home/wdjones/.openclaw/workspace")
CAPSULES_DIR = WORKSPACE / "data" / "time-capsules"
CAPSULES_FILE = CAPSULES_DIR / "capsules.json"

def load_capsules():
    """Load all capsules."""
    CAPSULES_DIR.mkdir(parents=True, exist_ok=True)
    if CAPSULES_FILE.exists():
        return json.loads(CAPSULES_FILE.read_text())
    return {"capsules": []}

def save_capsules(data):
    """Save capsules."""
    CAPSULES_FILE.write_text(json.dumps(data, indent=2))

def encode_message(msg: str) -> str:
    """Simple encoding (not secure, just hidden)."""
    return base64.b64encode(msg.encode()).decode()

def decode_message(encoded: str) -> str:
    """Decode message."""
    return base64.b64decode(encoded.encode()).decode()

def generate_id(msg: str, date: str) -> str:
    """Generate short ID for capsule."""
    h = hashlib.md5(f"{msg}{date}{datetime.now().isoformat()}".encode())
    return h.hexdigest()[:8]

def cmd_seal(args):
    """Seal a new time capsule."""
    if len(args) < 2:
        print("Usage: seal <message> --until YYYY-MM-DD")
        return
    
    message = args[0]
    
    # Parse --until
    open_date = None
    for i, arg in enumerate(args):
        if arg == "--until" and i + 1 < len(args):
            open_date = args[i + 1]
    
    if not open_date:
        # Default: 7 days from now
        from datetime import timedelta
        open_date = (datetime.now() + timedelta(days=7)).strftime("%Y-%m-%d")
    
    # Validate date
    try:
        datetime.strptime(open_date, "%Y-%m-%d")
    except ValueError:
        print(f"Invalid date format: {open_date} (use YYYY-MM-DD)")
        return
    
    capsule_id = generate_id(message, open_date)
    
    capsule = {
        "id": capsule_id,
        "sealed_at": datetime.now().isoformat(),
        "open_after": open_date,
        "content": encode_message(message),
        "opened": False,
    }
    
    data = load_capsules()
    data["capsules"].append(capsule)
    save_capsules(data)
    
    print(f"\n📦 Capsule sealed!")
    print(f"   ID: {capsule_id}")
    print(f"   Opens: {open_date}")
    print(f"   Contents: {'*' * min(len(message), 20)}")
    print()

def cmd_list(args):
    """List all capsules."""
    data = load_capsules()
    capsules = data.get("capsules", [])
    
    if not capsules:
        print("\nNo time capsules yet.\n")
        return
    
    today = datetime.now().strftime("%Y-%m-%d")
    
    print("\n╭────────────────────────────────────────╮")
    print("│          TIME CAPSULES                 │")
    print("╰────────────────────────────────────────╯\n")
    
    for c in capsules:
        status = "📬" if c["open_after"] <= today else "📦"
        opened = " (opened)" if c.get("opened") else ""
        print(f"  {status} {c['id']}  opens {c['open_after']}{opened}")
    
    print()

def cmd_open(args):
    """Open all capsules that are ready."""
    data = load_capsules()
    capsules = data.get("capsules", [])
    today = datetime.now().strftime("%Y-%m-%d")
    
    opened_any = False
    
    for c in capsules:
        if c["open_after"] <= today and not c.get("opened"):
            print(f"\n📬 Opening capsule {c['id']}...")
            print(f"   Sealed: {c['sealed_at'][:10]}")
            print(f"   Message:\n")
            print(f"   \"{decode_message(c['content'])}\"")
            print()
            c["opened"] = True
            opened_any = True
    
    if opened_any:
        save_capsules(data)
    else:
        ready = sum(1 for c in capsules if c["open_after"] <= today and not c.get("opened"))
        sealed = sum(1 for c in capsules if c["open_after"] > today)
        print(f"\nNo new capsules ready. ({sealed} still sealed)")
        print()

def cmd_peek(args):
    """Peek at a specific capsule (if allowed)."""
    if not args:
        print("Usage: peek <id>")
        return
    
    capsule_id = args[0]
    data = load_capsules()
    today = datetime.now().strftime("%Y-%m-%d")
    
    for c in data.get("capsules", []):
        if c["id"] == capsule_id:
            if c["open_after"] <= today or c.get("opened"):
                print(f"\n{decode_message(c['content'])}\n")
            else:
                days_left = (datetime.strptime(c["open_after"], "%Y-%m-%d") - datetime.now()).days
                print(f"\n🔒 This capsule opens in {days_left} days.\n")
                print("   Patience. The future will arrive.\n")
            return
    
    print(f"\nCapsule not found: {capsule_id}\n")

COMMANDS = {
    "seal": cmd_seal,
    "list": cmd_list,
    "open": cmd_open,
    "peek": cmd_peek,
}

def main():
    if len(sys.argv) < 2:
        print(__doc__)
        return
    
    cmd = sys.argv[1]
    args = sys.argv[2:]
    
    if cmd in COMMANDS:
        COMMANDS[cmd](args)
    else:
        print(f"Unknown command: {cmd}")
        print(f"Available: {', '.join(COMMANDS.keys())}")

if __name__ == "__main__":
    main()
