"""Screenshot capture of the active window."""

from __future__ import annotations

import base64
import logging
import time
from pathlib import Path
from typing import Optional, Tuple

from PIL import Image, ImageGrab

from ai_interview.config import SCREENSHOTS_DIR

logger = logging.getLogger(__name__)


def ensure_screenshots_dir() -> None:
    SCREENSHOTS_DIR.mkdir(parents=True, exist_ok=True)


def _get_active_window_bounds() -> Optional[Tuple[int, int, int, int]]:
    """Return (left, top, right, bottom) of the frontmost window on macOS."""
    try:
        import Quartz
        from AppKit import NSWorkspace

        front_app = NSWorkspace.sharedWorkspace().frontmostApplication()
        if front_app is None:
            return None
        front_pid = front_app.processIdentifier()

        window_list = Quartz.CGWindowListCopyWindowInfo(
            Quartz.kCGWindowListOptionOnScreenOnly | Quartz.kCGWindowListExcludeDesktopElements,
            Quartz.kCGNullWindowID,
        )

        for info in window_list:
            if info.get("kCGWindowOwnerPID") != front_pid:
                continue
            if info.get("kCGWindowLayer", 0) != 0:
                continue
            bounds = info.get("kCGWindowBounds")
            if bounds is None:
                continue
            x = int(bounds["X"])
            y = int(bounds["Y"])
            w = int(bounds["Width"])
            h = int(bounds["Height"])
            if w > 50 and h > 50:
                return (x, y, x + w, y + h)
    except Exception as exc:
        logger.debug("Window bounds detection failed: %s", exc)
    return None


def capture_active_window() -> Optional[Path]:
    """Capture the active window and save to screenshots dir.

    Returns the saved file path, or None on failure.
    """
    ensure_screenshots_dir()
    bounds = _get_active_window_bounds()

    try:
        img: Image.Image = ImageGrab.grab(bbox=bounds)  # None = full screen
    except Exception as exc:
        logger.error("Screenshot capture failed: %s", exc)
        return None

    path = SCREENSHOTS_DIR / f"screenshot_{int(time.time() * 1000)}.jpg"

    try:
        # Convert RGBA → RGB if needed (JPEG doesn't support alpha)
        if img.mode in ("RGBA", "P"):
            img = img.convert("RGB")
        img.save(path, "JPEG", quality=70)
    except Exception as exc:
        logger.error("Screenshot save failed: %s", exc)
        return None

    logger.info("Screenshot saved: %s", path.name)
    return path


def encode_screenshot_b64(path: Path) -> str:
    """Read a JPEG screenshot and return base64-encoded string.

    Re-encodes at lower quality if file is over 1.5 MB.
    """
    size = path.stat().st_size
    if size > 1_500_000:
        try:
            img = Image.open(path).convert("RGB")
            import io
            buf = io.BytesIO()
            img.save(buf, "JPEG", quality=40)
            return base64.b64encode(buf.getvalue()).decode()
        except Exception:
            pass
    return base64.b64encode(path.read_bytes()).decode()
