import time
import json
import os
from . import config
from . import ui


def save_session(hash_file, mode, stage, completed_attacks=None):
    """Persist cracking progress so --resume can skip completed attacks."""
    session = {
        "hash_file": hash_file,
        "mode": mode,
        "stage": stage,
        "completed_attacks": completed_attacks or [],
        "timestamp": time.time(),
    }
    try:
        with open(config.SESSION_FILE, 'w') as f:
            json.dump(session, f, indent=2)
    except Exception as e:
        ui.warn(f"Failed to save session: {e}")


def load_session():
    """Load previous session. Returns None if missing or stale (>24h)."""
    if not os.path.exists(config.SESSION_FILE):
        return None
    try:
        with open(config.SESSION_FILE, 'r') as f:
            session = json.load(f)
        if time.time() - session.get("timestamp", 0) > 86400:
            ui.warn("Session is >24 hours old — starting fresh")
            return None
        return session
    except Exception:
        return None


def clear_session():
    """Remove session file after a successful crack."""
    try:
        os.remove(config.SESSION_FILE)
    except FileNotFoundError:
        pass
