import requests
import urllib.parse
import time
import sys
import json
import os

from .config import API_KEY, BASE_URL, MEMORY_PATH


class Colors:
    RESET = "\033[0m"
    CYAN = "\033[1;36m"
    GREEN = "\033[1;32m"
    YELLOW = "\033[1;33m"
    RED = "\033[1;31m"


def typing_effect(text, delay=0.01):
    for c in text:
        sys.stdout.write(c)
        sys.stdout.flush()
        time.sleep(delay)
    print("")


class Memory:
    def __init__(self, path=MEMORY_PATH):
        self.path = path
        if not os.path.exists(path):
            with open(path, "w") as f:
                json.dump({"messages": []}, f)

    def load(self):
        with open(self.path, "r") as f:
            return json.load(f)

    def save(self, data):
        with open(self.path, "w") as f:
            json.dump(data, f, indent=2)

    def add(self, user, bot):
        data = self.load()
        data["messages"].append({"user": user, "bot": bot})
        data["messages"] = data["messages"][-20:]
        self.save(data)

    def context(self):
        data = self.load()
        ctx = ""
        for m in data["messages"]:
            ctx += f"User: {m['user']}\nAI: {m['bot']}\n"
        return ctx


class Client:
    def __init__(self, api_key=API_KEY, timeout=60, retries=3, color=True, animate=False, memory=True):
        self.api_key = api_key
        self.timeout = timeout
        self.retries = retries
        self.color = color
        self.animate = animate
        self.memory = Memory() if memory else None

    def ask(self, message: str):
        if self.memory:
            message = self.memory.context() + "\nUser: " + message

        encoded = urllib.parse.quote(message)
        url = f"{BASE_URL}?message={encoded}&api_key={self.api_key}"

        for attempt in range(self.retries):
            try:
                r = requests.get(url, timeout=self.timeout)
                data = r.json()

                if not data.get("success"):
                    return "API Error: request failed."

                reply = self._clean(data.get("response", ""))

                if self.memory:
                    self.memory.add(message, reply)

                if self.animate:
                    typing_effect(reply)
                    return ""

                if self.color:
                    return f"{Colors.CYAN}{reply}{Colors.RESET}"

                return reply

            except Exception as e:
                if attempt == self.retries - 1:
                    return f"Error: {e}"
                time.sleep(1)

    def chat(self):
        print(f"{Colors.GREEN}Ahmaedinfo AI Chat Mode Started{Colors.RESET}")
        print("Updates:", "https://t.me/Ahmaed_dev1")

        while True:
            user = input(f"{Colors.YELLOW}You: {Colors.RESET}")
            if user.lower() in ["exit", "quit"]:
                print("Goodbye!")
                break

            reply = self.ask(user)
            print(f"{Colors.CYAN}AI: {reply}{Colors.RESET}")

    def _clean(self, text):
        junk = [
            "[START OUTPUT)",
            "[END OUTPUT]-.-.-.-.",
            "(GODMODE: ENABLED"
        ]
        for j in junk:
            text = text.replace(j, "")
        return text.strip()


def ask(msg): 
    return Client().ask(msg)

def talk(msg): 
    return Client().ask(msg)

def AI(msg): 
    return Client().ask(msg)

def chat(): 
    return Client().chat()
