"""
vr open command - Open the web app to the agent function.
"""

import webbrowser
from pathlib import Path

import typer

from vr_cli.utils.config import FRONTEND_URL
from vr_cli.utils.utils import print_error, print_info
from vr_cli.utils.agent_lock import load_agent_lock


def open_cmd():
    """Open the web app to the agent function."""
    project_dir = Path.cwd()
    voicerun_dir = project_dir / ".voicerun"

    if not voicerun_dir.exists():
        print_error("Not a voicerun project (.voicerun directory not found)")
        print_info("Run 'vr init' to create a new project")
        raise typer.Exit(1)

    agent_lock = load_agent_lock(voicerun_dir)
    if not agent_lock:
        print_error("No agent.lock found. Run 'vr push' first to push your agent.")
        raise typer.Exit(1)

    agent_id = agent_lock.get("id")
    if not agent_id:
        print_error("Invalid agent.lock: missing agent ID")
        raise typer.Exit(1)

    function_id = agent_lock.get("functionId")

    # Build URL to agent function page
    if function_id:
        url = f"{FRONTEND_URL}/agents/{agent_id}/function?f={function_id}"
    else:
        url = f"{FRONTEND_URL}/agents/{agent_id}/function"

    print_info(f"Opening {url}")
    webbrowser.open(url)
