"""Configuration, constants, platform detection, and shared resources."""

import logging
import os
import platform
import sys

import anthropic
import pyautogui
from dotenv import load_dotenv

# ─── Platform Detection ────────────────────────────────────────────────────────

IS_WINDOWS    = sys.platform == "win32"
IS_MACOS      = sys.platform == "darwin"
IS_LINUX      = sys.platform.startswith("linux")
PLATFORM_NAME = "Windows" if IS_WINDOWS else ("macOS" if IS_MACOS else "Linux")


def _detect_os_version() -> str:
    if IS_WINDOWS:
        return f"Windows {platform.release()} ({platform.version()})"
    elif IS_MACOS:
        mac_ver = platform.mac_ver()[0]
        return f"macOS {mac_ver}" if mac_ver else "macOS"
    else:
        try:
            import distro  # type: ignore
            return f"Linux ({distro.name()} {distro.version()})"
        except ImportError:
            return f"Linux ({platform.release()})"


def _detect_shell() -> str:
    if IS_WINDOWS:
        return "PowerShell"
    shell = os.environ.get("SHELL", "")
    if "zsh" in shell:
        return "zsh"
    if "bash" in shell:
        return "bash"
    if "fish" in shell:
        return "fish"
    return os.path.basename(shell) if shell else "sh"


OS_VERSION = _detect_os_version()
SHELL_NAME = _detect_shell()

# Modifier key: Cmd on macOS, Ctrl elsewhere
MOD_KEY = "command" if IS_MACOS else "ctrl"

# ─── Environment / Config ──────────────────────────────────────────────────────

load_dotenv()

ANTHROPIC_API_KEY       = os.getenv("ANTHROPIC_API_KEY")
SCREENSHOT_INTERVAL     = float(os.getenv("SCREENSHOT_INTERVAL", 1.0))
MAX_STEPS               = int(os.getenv("MAX_STEPS", 100))
DEFAULT_MONITOR         = int(os.getenv("MONITOR_INDEX", 0))
MOUSE_DURATION          = 0.3
THINKING_BUDGET         = int(os.getenv("THINKING_BUDGET", 4096))
BASH_TIMEOUT            = int(os.getenv("BASH_TIMEOUT", 30))
MAX_CONTEXT_IMAGES      = int(os.getenv("MAX_CONTEXT_IMAGES", 15))
MODEL                   = os.getenv("MODEL", "claude-sonnet-4-5-20250929")
USER_HOME               = os.path.expanduser("~")
TASK_TIMEOUT            = int(os.getenv("TASK_TIMEOUT", 600))
SCREENSHOT_QUALITY      = int(os.getenv("SCREENSHOT_QUALITY", 75))
MAX_NUDGES              = 3

# Grid overlay — drawn on screenshots to give Claude precise coordinate labels
SCREENSHOT_GRID_OVERLAY = os.getenv("SCREENSHOT_GRID_OVERLAY", "true").lower() == "true"
GRID_SPACING            = int(os.getenv("GRID_SPACING", 100))  # px in display space

# Display dimensions Claude uses for coordinates
DISPLAY_WIDTH  = 1280
DISPLAY_HEIGHT = 800

if not ANTHROPIC_API_KEY:
    print("❌  ANTHROPIC_API_KEY not found. Add it to .env")
    sys.exit(1)

client = anthropic.Anthropic(api_key=ANTHROPIC_API_KEY)

pyautogui.FAILSAFE = False   # macOS: top-left corner no longer kills the agent
pyautogui.PAUSE    = 0.08

# ─── Logging ───────────────────────────────────────────────────────────────────

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler("agent.log", encoding="utf-8"),
    ],
)
log = logging.getLogger("genworker")
