import argparse
import threading
import time
import tkinter as tk
import sys

try:
    import pyperclip
except ImportError:
    print("Error: pyperclip not installed. Run: pip install clipgroq")
    sys.exit(1)

try:
    from groq import Groq
except ImportError:
    print("Error: groq not installed. Run: pip install clipgroq")
    sys.exit(1)

GROQ_MODEL = "llama-3.3-70b-versatile"
POLL_INTERVAL = 0.5  # seconds between clipboard checks
POPUP_DURATION = 2000  # ms before popup auto-closes


def ask_groq(client: "Groq", text: str) -> str:
    try:
        response = client.chat.completions.create(
            model=GROQ_MODEL,
            messages=[
                {
                    "role": "system",
                    "content": "Answer in ONE short sentence only. No extra explanation.",
                },
                {"role": "user", "content": text},
            ],
            max_tokens=150,
            temperature=0.3,
        )
        content = response.choices[0].message.content
        if not content:
            finish = response.choices[0].finish_reason
            return f"(No answer — finish reason: {finish})"
        return content.strip()
    except Exception as e:
        return f"Error: {e}"


def show_popup(answer: str):
    def _run():
        root = tk.Tk()
        root.overrideredirect(True)
        root.attributes("-topmost", True)
        root.attributes("-alpha", 0.95)
        root.configure(bg="#1c1c23")

        frame = tk.Frame(root, bg="#1c1c23", padx=24, pady=16)
        frame.pack()

        tk.Label(
            frame,
            text="Clipboard Agent",
            bg="#1c1c23",
            fg="#78a0ff",
            font=("Segoe UI", 9, "bold"),
        ).pack()

        tk.Label(
            frame,
            text=answer,
            bg="#1c1c23",
            fg="#ffffff",
            font=("Segoe UI", 13),
            wraplength=420,
            justify="center",
        ).pack(pady=(8, 0))

        tk.Button(
            frame,
            text="✕ Close",
            bg="#2a2a35",
            fg="#aaaaaa",
            relief="flat",
            font=("Segoe UI", 8),
            activebackground="#3a3a45",
            activeforeground="#ffffff",
            cursor="hand2",
            command=root.destroy,
        ).pack(pady=(12, 0))

        root.update_idletasks()
        w = root.winfo_width()
        h = root.winfo_height()
        sw = root.winfo_screenwidth()
        sh = root.winfo_screenheight()
        root.geometry(f"+{(sw - w) // 2}+{(sh - h) // 2}")
        root.config(highlightbackground="#3a3a50", highlightthickness=1)
        root.bind("<Button-1>", lambda e: root.destroy())
        root.after(POPUP_DURATION, root.destroy)
        root.mainloop()

    threading.Thread(target=_run, daemon=True).start()


def monitor_clipboard(api_key: str):
    client = Groq(api_key=api_key)
    last = ""

    print("\n  clipgroq is running.")
    print("  Copy any text -> Groq answers in a popup (closes in 2s).")
    print("  Press Ctrl+C to stop.\n")

    while True:
        try:
            current = pyperclip.paste()
        except Exception:
            current = ""

        if current and current != last:
            last = current
            text = current.strip()
            if len(text) < 3:
                time.sleep(POLL_INTERVAL)
                continue

            preview = text[:60] + ("..." if len(text) > 60 else "")
            print(f"[{time.strftime('%H:%M:%S')}] Copied: {preview}")

            answer = ask_groq(client, text)
            print(f"           -> {answer}\n")

            show_popup(answer)

        time.sleep(POLL_INTERVAL)


def main():
    parser = argparse.ArgumentParser(
        prog="clipgroq",
        description="Clipboard Agent — copy text, get a one-line Groq answer in a popup.",
    )
    parser.add_argument(
        "--key",
        required=True,
        metavar="GROQ_API_KEY",
        help="Your Groq API key (get one at console.groq.com)",
    )
    args = parser.parse_args()

    try:
        monitor_clipboard(api_key=args.key)
    except KeyboardInterrupt:
        print("\n  Stopped.")
        sys.exit(0)


if __name__ == "__main__":
    main()
