#!/usr/bin/env python3
"""Interactive DX captures popup — global list with origin tracking."""

import sys, os, time

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from muxlib import load_json, save_json, getch, readline_prompt, relative_time, now_iso, B, D, R, GREEN, YELLOW

DX_FILE = os.path.expanduser("~/.local/share/mux/dx.json")
origin = sys.argv[1] if len(sys.argv) > 1 else "unknown"


def next_id(d):
    if not d.get("items"):
        return 1
    return max(item.get("id", 0) for item in d["items"]) + 1


def main():
    while True:
        os.system("clear")
        d = load_json(DX_FILE)
        if not d:
            d = {"items": []}
        items = [item for item in d.get("items", []) if not item.get("done") and not item.get("filed")]

        print()
        if not items:
            print(f"  {B}DX Captures{R} (empty)")
            print()
            print("  No captures yet.")
            print()
            print(f"  Press {B}a{R} to add one, or {B}q{R} to close.")
            print()
        else:
            print(f"  {B}DX Captures{R} ({len(items)} item{'s' if len(items) != 1 else ''})")
            print()
            for i, item in enumerate(items, 1):
                orig = item.get("origin", "?")
                ts = relative_time(item.get("created_at", ""))
                print(f"  {B}{i}{R}. {item['text']}")
                print(f"     {D}{ts}  [{orig}]{R}")
            print()
            print(f"  Press {B}a{R} to add, {B}1{R}–{B}{len(items)}{R} to clear, {B}q{R} to close.")
            print()

        key = getch()

        if key in ("q", "Q", "\x1b", "\x03"):
            break

        if key in ("a", "A"):
            text = readline_prompt("  idea: ")
            if text:
                d = load_json(DX_FILE)
                if not d:
                    d = {"items": []}
                d["items"].append({
                    "id": next_id(d),
                    "text": text,
                    "created_at": now_iso(),
                    "origin": origin,
                    "done": False,
                    "filed": False,
                })
                save_json(DX_FILE, d)
                print(f"  {GREEN}✓{R} captured")
                time.sleep(0.5)
            continue

        if key.isdigit() and key != "0":
            d = load_json(DX_FILE)
            if not d:
                d = {"items": []}
            items = [item for item in d.get("items", []) if not item.get("done") and not item.get("filed")]
            idx = int(key) - 1
            if 0 <= idx < len(items):
                target_id = items[idx]["id"]
                for item in d["items"]:
                    if item["id"] == target_id:
                        item["done"] = True
                save_json(DX_FILE, d)
                print(f"  {GREEN}✓{R} cleared: {items[idx]['text']}")
                time.sleep(0.5)
            continue


main()
