"""
candy.cli — Interface ligne de commande v18
============================================

Commandes IA :
  candy --ask "prompt"                  → One-liner IA
  candy --ask "prompt" --lang EN        → Avec langue spécifiée
  candy --ask "prompt" --stream         → Streaming token par token
  candy --score "mon prompt"            → Score qualité du prompt
  candy --fix "mon prompt"              → Optimise un prompt
  candy --dry-run "prompt"              → Simule pipeline sans API
  candy --status                        → Statut de l'API
  candy --version                       → Version installée
  candy -- script.cdy                   → Exécute un fichier .cdy
  candy helper                          → Fenêtre Helper graphique

Commandes VPS :
  candy vps --"TOKEN"                   → Session interactive
  candy vps --ls --"TOKEN"              → Lister les fichiers
  candy vps --ls mon_dossier --"TOKEN"  → Lister un sous-dossier
  candy vps --upload "app.py" --"TOKEN" → Envoyer un fichier local
  candy vps --jobs --"TOKEN"            → Voir les scripts actifs
  candy vps --kill "job_id" --"TOKEN"   → Arrêter un script
  candy vps --quota --"TOKEN"           → Espace disque
  candy --efile "script.py" --"TOKEN"   → Exécuter un fichier hébergé
"""

import sys
import os
import json
from pathlib import Path

RESET  = "\033[0m"
CYAN   = "\033[96m"
GREEN  = "\033[92m"
RED    = "\033[91m"
YELLOW = "\033[93m"
GRAY   = "\033[90m"
WHITE  = "\033[97m"


def _read_prompt_arg(arg: str) -> str:
    if arg.endswith((".txt", ".cdy", ".md")) and Path(arg).exists():
        return Path(arg).read_text(encoding="utf-8").strip()
    return arg


def _extract_token(args: list):
    """
    Extrait le token VPS depuis les arguments.
    Forme acceptée : --"64hexchars"
    Retourne (token_or_None, args_restants)
    """
    token = None
    clean = []
    for a in args:
        # --"abcd...64chars"
        if a.startswith('--"') and a.endswith('"'):
            candidate = a[3:-1]
            if len(candidate) == 64 and all(c in "0123456789abcdefABCDEF" for c in candidate):
                token = candidate
                continue
        # --abcd...64chars (sans guillemets)
        if a.startswith("--") and len(a) == 66 and all(c in "0123456789abcdefABCDEF" for c in a[2:]):
            token = a[2:]
            continue
        clean.append(a)
    return token, clean


def _print_score(score_data: dict):
    s, grade, quality = score_data["score"], score_data["grade"], score_data["quality"]
    col = GREEN if grade == "A" else CYAN if grade == "B" else YELLOW if grade == "C" else "\033[33m" if grade == "D" else RED
    bar = "█" * int(30 * s / 100) + "░" * (30 - int(30 * s / 100))
    print(f"\n  {GRAY}Candy Prompt Score{RESET}")
    print(f"  {col}{bar}{RESET}  {col}{s}/100 · Grade {grade}{RESET}")
    print(f"  Qualité : {col}{quality}{RESET}  |  Mots : {score_data['words']}  |  Chars : {score_data['chars']}")
    print(f"  Personnalité détectée : {CYAN}{score_data['detected_personality']}{RESET}")
    if score_data["issues"]:
        print(f"\n  {col}⚠ Problèmes :{RESET}")
        for i in score_data["issues"]: print(f"    • {i}")
    if score_data["suggestions"]:
        print(f"\n  {CYAN}💡 Suggestions :{RESET}")
        for s in score_data["suggestions"]: print(f"    → {s}")
    print()


def main():
    args = sys.argv[1:]

    if not args:
        _print_help()
        return

    # candy --version
    if args[0] in ("--version", "-v"):
        from candy.banner import VERSION
        print(f"candy-ai v{VERSION}")
        return

    # candy --status
    if args[0] == "--status":
        try:
            from candy.modules.coding import Coding
            if Coding.is_online():
                ms = Coding.ping()
                print(f"{GREEN}● API en ligne{RESET}  ({ms:.0f} ms)")
            else:
                print(f"{RED}● API hors ligne{RESET}")
        except Exception as e:
            print(f"{RED}● Erreur : {e}{RESET}")
        return

    # candy --score
    if args[0] == "--score":
        if len(args) < 2:
            print('Usage : candy --score "mon prompt"')
            return
        from candy.core import Candy
        _print_score(Candy.score(_read_prompt_arg(args[1])))
        return

    # candy --fix
    if args[0] == "--fix":
        if len(args) < 2:
            print('Usage : candy --fix "mon prompt"')
            return
        from candy.core import Candy
        prompt = _read_prompt_arg(args[1])
        lang = args[args.index("--lang") + 1] if "--lang" in args else "FR"
        print(f"\n  {GRAY}Prompt original :{RESET} {prompt}")
        sb = Candy.score(prompt)
        print(f"  {GRAY}Score avant :{RESET} {sb['score']}/100 (Grade {sb['grade']})")
        print(f"\n  {CYAN}⚡ Optimisation...{RESET}")
        fixed = Candy.fix(prompt, lang=lang)
        sa = Candy.score(fixed)
        print(f"\n  {GREEN}✓ Prompt optimisé :{RESET}\n  {fixed}")
        print(f"\n  {GRAY}Score après :{RESET} {sa['score']}/100 (Grade {sa['grade']})")
        gain = sa["score"] - sb["score"]
        if gain > 0: print(f"  {GREEN}+{gain} points ↑{RESET}")
        print()
        return

    # candy --dry-run
    if args[0] == "--dry-run":
        if len(args) < 2:
            print('Usage : candy --dry-run "mon prompt"')
            return
        from candy.core import Candy
        prompt = _read_prompt_arg(args[1])
        r = Candy.dry_run(prompt)
        print(f"\n  {GRAY}╔══ Dry Run — Simulation ══╗{RESET}")
        print(f"  Prompt        : {prompt[:60]}{'...' if len(prompt)>60 else ''}")
        print(f"  Personnalité  : {CYAN}{r['would_use_personality']}{RESET}")
        col = GREEN if r['prompt_score'] >= 70 else RED
        print(f"  Score prompt  : {col}{r['prompt_score']}/100 (Grade {r['prompt_grade']}){RESET}")
        if r["issues"]: print(f"  Problèmes     : {', '.join(r['issues'])}")
        print(f"  API           : {YELLOW}{r['api_call']}{RESET}\n")
        return

    # candy --ask
    if args[0] == "--ask":
        if len(args) < 2:
            print('Usage : candy --ask "mon prompt" [--lang FR] [--stream]')
            return
        from candy.core import Candy
        prompt = _read_prompt_arg(args[1])
        lang   = args[args.index("--lang") + 1] if "--lang" in args else "FR"
        if "--stream" in args:
            for tok in Candy.stream(prompt, lang=lang):
                print(tok, end="", flush=True)
            print()
        else:
            print(Candy.ask(prompt, lang=lang))
        return

    # candy helper
    if args[0] == "helper":
        _launch_helper_window()
        return

    # candy -- script.cdy
    if args[0] == "--" and len(args) >= 2:
        sp = args[1]
        if not Path(sp).exists():
            print(f"{RED}Erreur : fichier '{sp}' introuvable.{RESET}")
            sys.exit(1)
        exec(compile(Path(sp).read_text(encoding="utf-8"), sp, "exec"), {"__name__": "__main__"})
        return

    # candy --efile "script.py" --"TOKEN"
    if args[0] == "--efile":
        if len(args) < 2:
            print('Usage : candy --efile "script.py" --"VOTRE_TOKEN"')
            return
        filename = args[1]
        token, _ = _extract_token(args[2:])
        if not token:
            print(f"{RED}Token manquant. Ajoute --\"VOTRE_TOKEN\" à la commande.{RESET}")
            print(f"  Récupère ton token sur candy-gate.hubworld.net → Dashboard → VPS")
            return
        from candy.vps import vps_efile
        vps_efile(token, filename)
        return

    # candy vps ...
    if args[0] == "vps":
        _handle_vps(args[1:])
        return

    _print_help()


def _handle_vps(args: list):
    from candy.vps import (
        vps_session, vps_ls, vps_upload,
        vps_jobs, vps_kill, vps_quota,
    )

    token, clean = _extract_token(args)

    if not token:
        _print_vps_help()
        return

    if not clean:
        vps_session(token)
        return

    sub = clean[0].lower()

    if sub == "--ls":
        path = clean[1] if len(clean) > 1 else "/"
        vps_ls(token, path)
    elif sub == "--upload":
        if len(clean) < 2:
            print('Usage : candy vps --upload "fichier.py" --"TOKEN"')
            return
        vps_upload(token, clean[1], clean[2] if len(clean) > 2 else None)
    elif sub == "--jobs":
        vps_jobs(token)
    elif sub == "--kill":
        if len(clean) < 2:
            print('Usage : candy vps --kill "job_id" --"TOKEN"')
            return
        vps_kill(token, clean[1])
    elif sub == "--quota":
        vps_quota(token)
    else:
        print(f"{YELLOW}Sous-commande VPS inconnue : '{sub}'{RESET}")
        _print_vps_help()


def _print_help():
    print(f"""
  {CYAN}🍬 candy-ai CLI v18{RESET}

  {GRAY}── IA ──────────────────────────────────────────{RESET}
  {GREEN}candy --ask{RESET} {GRAY}"prompt"{RESET}                  Appel one-liner
  {GREEN}candy --ask{RESET} {GRAY}"prompt" --stream{RESET}         Streaming token par token
  {GREEN}candy --ask{RESET} {GRAY}"prompt" --lang EN{RESET}        Langue spécifiée

  {GRAY}── Qualité des prompts ─────────────────────────{RESET}
  {GREEN}candy --score{RESET} {GRAY}"prompt"{RESET}                Score 0-100 + grade A→F
  {GREEN}candy --fix{RESET} {GRAY}"prompt"{RESET}                  Auto-optimise un prompt
  {GREEN}candy --dry-run{RESET} {GRAY}"prompt"{RESET}              Simule sans appeler l'API

  {GRAY}── VPS ─────────────────────────────────────────{RESET}
  {GREEN}candy vps{RESET} {GRAY}--"TOKEN"{RESET}                   Session interactive
  {GREEN}candy vps --ls{RESET} {GRAY}--"TOKEN"{RESET}              Lister les fichiers
  {GREEN}candy vps --upload{RESET} {GRAY}"app.py" --"TOKEN"{RESET} Envoyer un fichier
  {GREEN}candy vps --jobs{RESET} {GRAY}--"TOKEN"{RESET}            Scripts actifs
  {GREEN}candy vps --kill{RESET} {GRAY}"id" --"TOKEN"{RESET}       Arrêter un script
  {GREEN}candy vps --quota{RESET} {GRAY}--"TOKEN"{RESET}           Espace disque
  {GREEN}candy --efile{RESET} {GRAY}"script.py" --"TOKEN"{RESET}   Exécuter (streaming)

  {GRAY}── Outils ──────────────────────────────────────{RESET}
  {GREEN}candy helper{RESET}                         Fenêtre Helper graphique
  {GREEN}candy -- script.cdy{RESET}                  Exécute un fichier .cdy
  {GREEN}candy --status{RESET}                       Statut de l'API
  {GREEN}candy --version{RESET}                      Version installée

  {GRAY}  Token VPS : candy-gate.hubworld.net → Dashboard → VPS{RESET}
""")


def _print_vps_help():
    print(f"""
  {CYAN}🖥️  candy VPS — Commandes{RESET}

  {GREEN}candy vps{RESET} {GRAY}--"TOKEN"{RESET}                        Session interactive
  {GREEN}candy vps --ls{RESET} {GRAY}--"TOKEN"{RESET}                   Lister /
  {GREEN}candy vps --ls{RESET} {GRAY}dossier --"TOKEN"{RESET}           Lister un dossier
  {GREEN}candy vps --upload{RESET} {GRAY}"app.py" --"TOKEN"{RESET}      Envoyer un fichier
  {GREEN}candy vps --jobs{RESET} {GRAY}--"TOKEN"{RESET}                 Scripts actifs
  {GREEN}candy vps --kill{RESET} {GRAY}"job_id" --"TOKEN"{RESET}        Arrêter un script
  {GREEN}candy vps --quota{RESET} {GRAY}--"TOKEN"{RESET}                Espace disque
  {GREEN}candy --efile{RESET} {GRAY}"script.py" --"TOKEN"{RESET}        Exécuter (streaming)

  {GRAY}  Token : candy-gate.hubworld.net → Dashboard → VPS{RESET}
""")


def _launch_helper_window():
    try:
        import tkinter as tk
        from tkinter import scrolledtext
        import threading

        root = tk.Tk()
        root.title("🍬 Candy Helper v18")
        root.geometry("700x540")
        root.configure(bg="#ffffff")

        header = tk.Frame(root, bg="#f5f5f7", pady=12)
        header.pack(fill="x")
        tk.Label(header, text="🍬 Candy Helper", font=("Inter", 14, "bold"),
                 bg="#f5f5f7", fg="#1d1d1f").pack(side="left", padx=20)
        tk.Label(header, text="v18", font=("Inter", 10),
                 bg="#f5f5f7", fg="#6e6e73").pack(side="left")

        input_frame = tk.Frame(root, bg="#ffffff", padx=20, pady=12)
        input_frame.pack(fill="x")
        tk.Label(input_frame, text="Décris ce que tu veux faire :",
                 font=("Inter", 11), bg="#ffffff", fg="#1d1d1f").pack(anchor="w")
        task_input = tk.Text(input_frame, height=4, font=("Courier New", 11),
                             bg="#f5f5f7", fg="#1d1d1f", relief="flat",
                             padx=10, pady=8, wrap="word")
        task_input.pack(fill="x", pady=(6, 0))

        btn_frame  = tk.Frame(root, bg="#ffffff", padx=20, pady=8)
        btn_frame.pack(fill="x")
        status_lbl = tk.Label(btn_frame, text="", font=("Inter", 10),
                              bg="#ffffff", fg="#6e6e73")
        status_lbl.pack(side="left")

        out_frame = tk.Frame(root, bg="#ffffff", padx=20, pady=(0, 20))
        out_frame.pack(fill="both", expand=True)
        output = scrolledtext.ScrolledText(
            out_frame, font=("Courier New", 11), bg="#1d1d1f", fg="#e8e8ed",
            relief="flat", state="normal", padx=12, pady=10, wrap="word"
        )
        output.pack(fill="both", expand=True)

        def _show_output(code):
            output.config(state="normal")
            output.delete("1.0", "end")
            output.insert("1.0", code)
            status_lbl.config(text="✅ Prêt")

        def generate():
            task = task_input.get("1.0", "end").strip()
            if not task: return
            status_lbl.config(text="⚡ Génération...")
            def run():
                try:
                    from candy import Helper
                    code = Helper.write("chatbot", lang="FR", module="Full") if task == "chatbot" else Helper.write(task)
                    root.after(0, lambda: _show_output(code))
                except Exception as e:
                    root.after(0, lambda: _show_output(f"# Erreur : {e}"))
            threading.Thread(target=run, daemon=True).start()

        def copy_output():
            code = output.get("1.0", "end").strip()
            root.clipboard_clear()
            root.clipboard_append(code)
            status_lbl.config(text="✅ Copié !")

        tk.Button(btn_frame, text="Générer", font=("Inter", 11, "bold"),
                  bg="#0071e3", fg="white", relief="flat", padx=16, pady=6,
                  cursor="hand2", command=generate).pack(side="right", padx=(8, 0))
        tk.Button(btn_frame, text="Copier", font=("Inter", 11),
                  bg="#f5f5f7", fg="#1d1d1f", relief="flat", padx=16, pady=6,
                  cursor="hand2", command=copy_output).pack(side="right")

        root.mainloop()

    except ImportError:
        print(f"{RED}tkinter non disponible. Utilise candy --ask{RESET}")


if __name__ == "__main__":
    main()
