"""Shared utility functions and constants for CLI and chat."""

import os
import platform
import subprocess as sp
import webbrowser
from pathlib import Path

# Tools with special display handling
MESSAGE_TOOLS = frozenset({"send_message_to_user"})
ASK_TOOLS = frozenset({"ask_user", "ask_user_with_examples", "ask_user_for_confirmation"})


def open_url_in_browser(url: str, token: str) -> None:
    """Open a URL in the default browser with a JWT query parameter."""
    separator = "&" if "?" in url else "?"
    webbrowser.open(f"{url}{separator}jwt={token}")


def unique_path(path: Path) -> Path:
    """Add a numeric suffix if the file already exists (e.g. file (1).txt)."""
    if not path.exists():
        return path
    stem, suffix = path.stem, path.suffix
    n = 1
    while path.exists():
        path = path.parent / f"{stem} ({n}){suffix}"
        n += 1
    return path


def find_workspace_file(workspace_files: list[dict[str, str]], name: str) -> str | None:
    """Find a workspace file URL by name or path (path match first, then basename)."""
    basename = name.rsplit("/", 1)[-1] if "/" in name else name
    normalized = name.lstrip("/")
    # First pass: path match (most specific — handles same-name files in different folders)
    for wf in workspace_files:
        if wf["path"].endswith(normalized):
            return wf["url"]
    # Second pass: basename match (for simple filenames like "index.html")
    for wf in workspace_files:
        if wf["name"] == basename:
            return wf["url"]
    return None


def open_with_system_app(path: Path) -> None:
    """Open a file with the system's default application."""
    system = platform.system()
    if system == "Windows":
        os.startfile(path)  # noqa: S606
    elif system == "Darwin":
        sp.run(["open", str(path)], check=False)
    else:
        sp.run(["xdg-open", str(path)], check=False)
