#!/usr/bin/env python3
import sys
import os
import json
import argparse
import gi
gi.require_version('Gtk', '4.0')
gi.require_version('Adw', '1')
from gi.repository import Gtk, Adw, GLib

from .theme import get_colors
from .schema import validate
from .backends.gui import GuiBackend
from .artixgui.mode_select import run_mode_selection


def main():
    Adw.init()

    sys.stderr.write("=== CLI.PY STARTED ===\n")
    sys.stderr.flush()

    parser = argparse.ArgumentParser(description="GTK4 GUI frontend")
    parser.add_argument("--mode", choices=["auto", "gui", "config"], default="auto",
                        help="Display mode: config = persistent configuration window")
    parser.add_argument("--input", "-i", type=argparse.FileType("r"),
                        default=sys.stdin)
    parser.add_argument("--output", "-o", type=argparse.FileType("w"),
                        default=sys.stdout)
    parser.add_argument("--color-title", type=int, default=None)
    parser.add_argument("--color-accent", type=int, default=None)
    args = parser.parse_args()

    if args.mode == "config":
        state_file = "/tmp/artix-installer/state.conf"
        os.makedirs(os.path.dirname(state_file), exist_ok=True)
        try:
            run_mode_selection(state_file)
        except Exception as e:
            print(f"GUI mode selection failed: {e}", file=sys.stderr)
            sys.exit(1)
        sys.exit(0)

    try:
        raw = args.input.read()
        data = json.loads(raw) if raw.strip() else {}
    except json.JSONDecodeError as e:
        json.dump({"error": f"Invalid input JSON: {e}", "cancelled": True}, args.output)
        sys.exit(1)

    try:
        data = validate(data)
    except Exception as e:
        json.dump({"error": str(e), "cancelled": True}, args.output)
        sys.exit(1)

    title_color, accent_color = get_colors(args.color_title, args.color_accent)

    if args.mode in ("gui", "auto") and os.environ.get("DISPLAY"):
        backend = GuiBackend()
    else:
        json.dump({"error": "No DISPLAY available – cannot start GUI", "cancelled": True}, args.output)
        sys.exit(1)

    try:
        result = backend.run(data, title_color=title_color, accent_color=accent_color)
    except Exception as e:
        result = {"error": str(e), "cancelled": True}

    json.dump(result, sys.stderr)
    sys.stderr.flush()


if __name__ == "__main__":
    main()