# uf/engine.py
import time
import random
import os
import math

# -----------------------------
# Tokenizer
# -----------------------------
def tokenize(line):
    tokens = []
    current = ""
    in_string = False
    for char in line:
        if char == '"':
            in_string = not in_string
            current += char
        elif char.isspace() and not in_string:
            if current:
                tokens.append(current)
                current = ""
        else:
            current += char
    if current:
        tokens.append(current)
    return tokens

# -----------------------------
# Base Mode Class
# -----------------------------
class BaseMode:
    def __init__(self, variables):
        self.variables = variables

    def show_commands(self):
        raise NotImplementedError

    def execute(self, tokens):
        raise NotImplementedError

# -----------------------------
# UF Engine Class
# -----------------------------
class UFEngine:
    def __init__(self):
        self.variables = {}
        self.mode_classes = {}
        self.current_mode = None
        self.mode_name = "uf"

    def register_mode(self, name, mode_class):
        self.mode_classes[name.lower()] = mode_class

    def select_mode(self, name=None):
        if name and name.lower() in self.mode_classes:
            self.mode_name = name.lower()
        else:
            # Prompt user
            while True:
                name = input("Select mode (UF / iUF / nUF / dnUF): ").strip().lower()
                if name in self.mode_classes:
                    self.mode_name = name
                    break
        self.current_mode = self.mode_classes[self.mode_name](self.variables)
        print(f"Loaded mode: {self.mode_name.upper()}")
        if self.mode_name == "uf":
            self.current_mode.show_commands()

    def execute_line(self, line):
        tokens = tokenize(line)
        if not tokens:
            return
        self.current_mode.execute(tokens)

    def run_repl(self):
        while True:
            try:
                line = input(f"{self.mode_name.upper()} > ").strip()
            except EOFError:
                print("\nExiting UF Engine...")
                break
            if line.lower() == "exit":
                print("Exiting UF Engine...")
                break
            self.execute_line(line)

    def run_file(self, filename):
        try:
            with open(filename, "r") as f:
                for line in f:
                    line = line.strip()
                    if not line or line.startswith("#"):
                        continue
                    self.execute_line(line)
        except FileNotFoundError:
            print(f"File not found: {filename}")

# -----------------------------
# Mode Classes
# -----------------------------
from .modes import UFMode, iUFMode, nUFMode, dnUFMode  # We'll create a modes package later