"""
Agent lock file utilities.

The agent.lock file stores the agent ID and function ID for a voicerun project,
allowing the CLI to track which remote agent corresponds to the local project.
"""

import json
from pathlib import Path
from typing import Optional

AGENT_LOCK_FILE = "agent.lock"


def load_agent_lock(voicerun_dir: Path) -> Optional[dict]:
    """Load the agent lock file if it exists.

    Args:
        voicerun_dir: Path to the .voicerun directory

    Returns:
        Dictionary with lock data (id, functionId) or None if not found/invalid
    """
    lock_path = voicerun_dir / AGENT_LOCK_FILE
    if lock_path.exists():
        try:
            with open(lock_path, "r") as f:
                return json.load(f)
        except Exception:
            return None
    return None


def save_agent_lock(voicerun_dir: Path, lock_data: dict) -> bool:
    """Save the agent lock file.

    Args:
        voicerun_dir: Path to the .voicerun directory
        lock_data: Dictionary with lock data (id, functionId)

    Returns:
        True if saved successfully, False otherwise
    """
    lock_path = voicerun_dir / AGENT_LOCK_FILE
    try:
        with open(lock_path, "w") as f:
            json.dump(lock_data, f, indent=2)
        return True
    except Exception:
        return False
