import random
import os
import time
from tkinter import filedialog, Tk
import sys
import json
import platform
import re

ValueErrorVar = "ERROR: Invalid number"
ErrorRange = "ERROR: Invalid range"

def timer(n):
    return time.sleep(n)

def sum(n, m):
    return n + m

def sub(n, m):
    return n - m

def mult(n, m):
    return n * m

def div(n, m):
    if m != 0:
        return n / m
    else:
        return "ERROR: Division by 0"

def sqrt(n):
    if n >= 0:
        return n ** 0.5
    else:
        return "ERROR: Negative square root"

def pow(n, m):
    return n ** m

def binary(n):
    return bin(n)[2:]
    
def clear():
    if 'google.colab' in sys.modules:
        from IPython.display import clear_output
        clear_output()
    else:
        if os.name == "posix":
            os.system("clear")
        else:
            os.system("cls")
        
def randint(n, m):
    if n < m:
        return random.randint(n, m)
    else:
        return "ERROR: Invalid random number"

def randchoice(lista):
    return random.choice(lista)

def save(archivo_nombre, texto_contenido):
    # 1. Check if running in Google Colab
    if 'google.colab' in sys.modules:
        ruta_colab = f"{archivo_nombre}.txt"
        try:
            with open(ruta_colab, "a", encoding="utf-8") as f:
                f.write(texto_contenido + "\n")
            return f"Success: Saved in Colab environment as {ruta_colab}"
        except Exception as e:
            return f"ERROR: Could not save file in Colab. {e}"

    # 2. PC Mode (Windows/Linux/Mac) with Window Selector
    try:
        from tkinter import filedialog, Tk
        root = Tk()
        root.withdraw() 
        root.attributes("-topmost", True) 

        print("Select the folder where you want to save your file...")
        carpeta_seleccionada = filedialog.askdirectory(title="Select Save Folder")
        
        root.destroy()

        if not carpeta_seleccionada:
            return "Operation cancelled by the user."

        # Create the full path
        ruta_final = os.path.join(carpeta_seleccionada, f"{archivo_nombre}.txt")
        
        with open(ruta_final, "a", encoding="utf-8") as f:
            f.write(texto_contenido + "\n")
        
        return f"Success: File saved at {ruta_final}"
        
    except Exception as e:
        return f"ERROR: An unexpected error occurred on PC. {e}"


def typewriter(text, speed):
    """typewriter(text, speed)"""
    for char in text:
        sys.stdout.write(char)
        sys.stdout.flush()
        timer(speed)
    print()


def save_json(file_name, data):
    try:
        with open(f"{file_name}.json", "w") as f:
            json.dump(data, f, indent=4)
        return f"Success: Data saved as {file_name}.json"
    except Exception as e:
        return f"Error: {e}"

def info():
    return f"OS: {platform.system()} | Python: {platform.python_version()}"

def hexcolor(hex_val, text):
    """hexcolor("RRGGBB", "text")"""
    try:
        # Convierte Hexadecimal a RGB
        r = int(hex_val[0:2], 16)
        g = int(hex_val[2:4], 16)
        b = int(hex_val[4:6], 16)
        
        # Devuelve el código ANSI de color + texto + reset
        return f"\033[38;2;{r};{g};{b}m{text}\033[0m"
    except:
        # Si algo sale mal, devuelve el texto normal para no romper el programa
        return text

def help():
    print("Help page")
    try:
        Page = int(input("\nPage (1 - 4): "))
        if Page not in range(1, 5):
            print(ErrorRange)
            return
    except ValueError:
        print(ValueErrorVar)
        return
    if Page == 1:
        print("\nsum(number, number2): number + number2")
        print("sub(number, number2): number - number2")
        print("mult(number, multiplier): number * multiplier")
        print("div(number, divider): number / divisor IF the divisor is not equal to 0")
        print("timer(number): Pause execution for a defined amount of time (time = number value)")
        input("\nOK")
        clear()
    elif Page == 2:
        print("\nsqrt(number): square root of number IF number does not have a negative value (less than 0)")
        print("pow(number, power): number ^ power")
        print("binary(number): Convert number to binary without the 0b prefix (we know the prefix is ​annoying)")
        print("clear(): Cleans the terminal (code output), compatible with Colab (Google Colaboratory)")
        print("randint(min, max): Choose a random number between the minimum and maximum values")
        input("\nOK")
        clear()
    elif Page == 3:
        print("\nrandchoice(list): choose a random item from the list")
        print("save(name, text): Save the text to a text file in a custom path (ONLY PC). Colab compatible")
        print("typewriter(text, speed): Prints text character by character with a custom delay.")
        print('hexcolor("RRGGBB", text): Color your text using Hexadecimal codes (RRGGBB)')
        print("save_json(name, text): Save the text to a .json file in a custom path (ONLY PC). Colab compatible")
        input("\nOK")
        clear()
    elif Page == 4:
        print("info(): Print your Python version and your operating system")
        input("\nOK")
        clear()

help()