import os
import sys
import time
import shutil
import subprocess
import tarfile
import hashlib
from pathlib import Path
from typing import Any
from config import Config
from api_client import ApiClient
from logger import get_logger
import update

log = get_logger("update_action")


def swap_directories_atomic(src_dir: Path, dest_link: Path):
    if hasattr(os, "symlink"):
        try:
            temp_link = dest_link.parent / f"{dest_link.name}_temp"
            if temp_link.exists() or temp_link.is_symlink():
                temp_link.unlink()
            os.symlink(src_dir, temp_link)
            os.replace(temp_link, dest_link)
            return
        except OSError as e:
            log.warning("Symlink creation failed (%s), falling back to directory swap", e)
            
    if dest_link.exists() or dest_link.is_symlink():
        if dest_link.is_symlink():
            dest_link.unlink()
        else:
            shutil.rmtree(dest_link)
    shutil.copytree(src_dir, dest_link)


def handle_agent_update(payload: dict[str, Any], config: Config, api_client: ApiClient) -> dict[str, Any]:
    """Execute the agent self-update process by calling update.self_update."""
    log.info("Starting agent self-update...")
    try:
        update.self_update(config, api_client, payload)
        return {"success": True, "message": "Self-update sequence completed."}
    except Exception as exc:
        log.error("Self-update failed: %s", exc)
        return {"success": False, "error": str(exc)}
