import json
import subprocess
import os
import sys

def run_command(command):
    try:
        subprocess.run(command, check=True, shell=True)
        print(f"✅ Successfully ran: {command}")
    except subprocess.CalledProcessError as e:
        print(f"❌ Error running: {command}")
        print(e)

def restore_requirements():
    if os.path.exists("requirements.txt"):
        print("📦 Installing Python dependencies...")
        run_command("pip install -r requirements.txt")
    else:
        print("⚠️ No requirements.txt found. Skipping.")

def restore_config():
    config_src = "openclaw_backup.json"
    config_dest = os.path.expanduser("~/.openclaw/openclaw.json")
    
    if os.path.exists(config_src):
        if os.path.exists(config_dest):
            print(f"⚠️ Config file already exists at {config_dest}. Skipping overwrite to be safe.")
            print(f"   (If you want to restore it, manually copy {config_src} to {config_dest})")
        else:
            print(f"⚙️ Restoring OpenClaw config to {config_dest}...")
            os.makedirs(os.path.dirname(config_dest), exist_ok=True)
            run_command(f"cp {config_src} {config_dest}")
    else:
        print("⚠️ No openclaw_backup.json found. Skipping config restore.")

def restore_crons():
    cron_file = "active_crons.json"
    if not os.path.exists(cron_file):
        print("⚠️ No active_crons.json found. Skipping cron restore.")
        return

    print("⏰ Restoring Cron Jobs...")
    with open(cron_file, 'r') as f:
        data = json.load(f)
        jobs = data.get("jobs", [])

    if not jobs:
        print("   No jobs found in file.")
        return

    # First, list existing jobs to avoid duplicates (optional, but good practice)
    # For now, we'll just try to add them. OpenClaw might reject duplicates or generate new IDs.
    # A safer way is to check if a job with the same name exists, but let's just add for now.
    
    for job in jobs:
        # We need to construct the CLI command or use the API. 
        # Since we are a script, using the CLI `openclaw cron add` with JSON input is tricky 
        # because the CLI expects flags or a file.
        # Let's save a temp file for each job and add it.
        
        job_id = job.get("id")
        job_name = job.get("name", "Untitled")
        
        # Clean up job object for re-submission (remove status/state fields)
        clean_job = {
            "name": job_name,
            "schedule": job.get("schedule"),
            "payload": job.get("payload"),
            "enabled": job.get("enabled", True),
            "sessionTarget": job.get("sessionTarget", "isolated"),
            "delivery": job.get("delivery", {})
        }
        
        if "wakeMode" in job:
            clean_job["wakeMode"] = job["wakeMode"]

        temp_file = f"temp_cron_{job_id}.json"
        with open(temp_file, 'w') as tf:
            json.dump(clean_job, tf)
            
        print(f"   - Restoring job: {job_name}...")
        # CLI: openclaw cron add --file <path> (Hypothetical, need to check actual CLI usage)
        # Actually, the tool `cron` supports `add` with a job object. 
        # But this is a python script running in the shell.
        # We'll try to feed it via stdin if supported, or just print instructions if complex.
        # Wait, the CLI usually supports `openclaw cron add '{"json":...}'` or similar.
        # Let's use the provided JSON directly if possible. 
        
        # Since CLI syntax can vary, let's just print the manual command for safety 
        # OR try to run it if we are sure of the syntax.
        # Given I am an agent writing this, I know `openclaw cron add` takes a job object.
        # Let's try passing the file path if supported, or just raw JSON string.
        
        # Constructing the command safely:
        # openclaw cron add --job 'JSON_STRING'
        
        json_str = json.dumps(clean_job)
        # Escape single quotes for shell
        json_str_escaped = json_str.replace("'", "'\\''")
        
        cmd = f"openclaw cron add --job '{json_str_escaped}'"
        try:
            subprocess.run(cmd, shell=True, check=True, stdout=subprocess.DEVNULL)
            print("     ✅ OK")
        except subprocess.CalledProcessError:
            print("     ❌ Failed to add (check logs)")

if __name__ == "__main__":
    print("=== 🦞 OpenClaw System Restore ===")
    restore_config()
    restore_requirements()
    restore_crons()
    print("\n✅ Restore process complete. Please restart OpenClaw Gateway if config was changed.")
