#!/usr/bin/env python3
"""Pi LXDE wallpaper helpers — OUT OF ORDER during watchdog backoff."""

from __future__ import annotations

import argparse
import subprocess
from pathlib import Path

APP_ROOT = Path(__file__).resolve().parent
DEFAULT_OUT_OF_ORDER = APP_ROOT / "content" / "out_of_order_1920x1080.png"
_STRIP_WALLPAPER = APP_ROOT / "Assets" / "Shared" / "1920x360" / "pot_dyzine_logo.png"
_TBX_WALLPAPER = APP_ROOT / "Assets" / "Shared" / "1920x1080" / "POG_Render_02.png"
SAVED_WALLPAPER_FILE = APP_ROOT / "run" / "wallpaper.original.txt"
OUT_OF_ORDER_FLAG = APP_ROOT / "run" / "out_of_order.active"


def _display_mode() -> str:
    cfg = APP_ROOT / "config.ini"
    try:
        text = cfg.read_text(encoding="utf-8", errors="replace")
    except OSError:
        return "TBX"
    for line in text.splitlines():
        s = line.split(";", 1)[0].strip()
        if s.lower().startswith("display_mode"):
            parts = s.split("=", 1)
            if len(parts) == 2:
                return parts[1].strip().upper() or "TBX"
    return "TBX"


def default_wallpaper_path() -> Path:
    if _display_mode() == "STRIP" and _STRIP_WALLPAPER.is_file():
        return _STRIP_WALLPAPER
    if _TBX_WALLPAPER.is_file():
        return _TBX_WALLPAPER
    return _STRIP_WALLPAPER if _STRIP_WALLPAPER.is_file() else _TBX_WALLPAPER


# Back-compat for imports that read DEFAULT_WALLPAPER at import time.
DEFAULT_WALLPAPER = default_wallpaper_path()


def _run_pcmanfm_set(path: Path) -> bool:
    try:
        proc = subprocess.run(
            ["pcmanfm", "--set-wallpaper", str(path)],
            capture_output=True,
            text=True,
            timeout=15,
            check=False,
        )
        return proc.returncode == 0
    except (OSError, subprocess.TimeoutExpired):
        return False


def ensure_default_wallpaper() -> bool:
    wall = default_wallpaper_path()
    if not wall.is_file():
        return False
    return _run_pcmanfm_set(wall)


def ensure_out_of_order_image(image_path: Path | None = None) -> Path:
    path = Path(image_path) if image_path else DEFAULT_OUT_OF_ORDER
    if path.is_file():
        return path
    wall = default_wallpaper_path()
    if wall.is_file():
        return wall
    return path


def enter_out_of_order(image_path: Path | None = None) -> bool:
    OUT_OF_ORDER_FLAG.parent.mkdir(parents=True, exist_ok=True)
    wall = default_wallpaper_path()
    if not OUT_OF_ORDER_FLAG.is_file() and not SAVED_WALLPAPER_FILE.is_file():
        SAVED_WALLPAPER_FILE.write_text(str(wall), encoding="utf-8")
    image = ensure_out_of_order_image(image_path)
    ok = _run_pcmanfm_set(image)
    if ok:
        OUT_OF_ORDER_FLAG.write_text(str(image), encoding="utf-8")
    return ok


def exit_out_of_order() -> bool:
    if not OUT_OF_ORDER_FLAG.is_file():
        return True
    restored = False
    if SAVED_WALLPAPER_FILE.is_file():
        try:
            original = Path(SAVED_WALLPAPER_FILE.read_text(encoding="utf-8").strip())
            if original.is_file():
                restored = _run_pcmanfm_set(original)
        except OSError:
            restored = False
    try:
        OUT_OF_ORDER_FLAG.unlink(missing_ok=True)
        SAVED_WALLPAPER_FILE.unlink(missing_ok=True)
    except OSError:
        pass
    return restored


def is_out_of_order_active() -> bool:
    return OUT_OF_ORDER_FLAG.is_file()


def main() -> int:
    parser = argparse.ArgumentParser(description="Pi LXDE wallpaper control")
    parser.add_argument("--show", action="store_true")
    parser.add_argument("--clear", action="store_true")
    parser.add_argument("--ensure", action="store_true")
    args = parser.parse_args()
    if args.show:
        return 0 if enter_out_of_order() else 1
    if args.clear:
        return 0 if exit_out_of_order() else 1
    if args.ensure:
        return 0 if ensure_default_wallpaper() else 1
    print(f"out_of_order_active={is_out_of_order_active()}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
