import sys

def ifs(lines):
    variables = {}  # Store variables
    loop_stack = []  # Track loop execution state
    functions = {}  # Store function definitions: {name: (parameters, body_commands, start_index)}
    call_stack = []  # Track function calls for return addresses and local scopes

    def parse_line(line):
        """Parse a line, handling quotes properly"""
        tokens = []
        current_token = ""
        in_quotes = False
        quote_char = None
        escape_next = False

        for char in line:
            if escape_next:
                current_token += char
                escape_next = False
            elif char == '\\':
                escape_next = True
            elif char in ['"', "'"]:
                if not in_quotes:
                    in_quotes = True
                    quote_char = char
                    if current_token.strip():
                        tokens.extend(current_token.strip().split())
                    current_token = ""
                elif char == quote_char:
                    in_quotes = False
                    quote_char = None
                    tokens.append(current_token)
                    current_token = ""
                else:
                    current_token += char
            elif char in [' ', '\t'] and not in_quotes:
                if current_token:
                    tokens.append(current_token)
                    current_token = ""
            else:
                current_token += char

        if current_token:
            tokens.append(current_token)

        return tokens

    def resolve_value(token, variables):
        """Resolve a token to its actual value (variable or literal)"""
        if token in variables:
            return variables[token]
        if (token.startswith('"') and token.endswith('"')) or (token.startswith("'") and token.endswith("'")):
            return token[1:-1]
        return token

    def evaluate_condition(condition_tokens, variables):
        """Evaluate a condition with multiple operators"""
        if len(condition_tokens) < 3:
            return False

        left = resolve_value(condition_tokens[0], variables)
        operator = condition_tokens[1]
        right = resolve_value(condition_tokens[2], variables)

        try:
            left_num = float(left) if isinstance(left, str) and left.replace('.', '', 1).replace('-', '', 1).isdigit() else left
            right_num = float(right) if isinstance(right, str) and right.replace('.', '', 1).replace('-', '', 1).isdigit() else right
        except:
            left_num, right_num = left, right

        if operator in ["equals", "=="]:
            return str(left) == str(right)
        elif operator in ["notequals", "!="]:
            return str(left) != str(right)
        elif operator in ["greater", ">"]:
            return left_num > right_num
        elif operator in ["greaterequals", ">="]:
            return left_num >= right_num
        elif operator in ["less", "<"]:
            return left_num < right_num
        elif operator in ["lessequals", "<="]:
            return left_num <= right_num
        elif operator == "contains":
            return str(right) in str(left)
        elif operator == "in":
            return str(left) in str(right)

        return False

    def execute_single_command(i, variables, all_commands):
        """Execute a single command - core interpreter logic"""
        if not i:
            return

        # --- PRINT ---
        if i[0] == "print":
            output_parts = []
            for word in i[1:]:
                output_parts.append(str(variables.get(word, word)))
            output_str = " ".join(output_parts)
            print(output_str)

        # --- SET VARIABLE ---
        elif i[0] == "set":
            if len(i) >= 3:
                var_name = i[1]
                value_str = " ".join(i[2:])
                try:
                    variables[var_name] = eval(value_str, {"__builtins__": None}, variables)
                except:
                    variables[var_name] = value_str

        # --- FUNCTION DEFINITIONS ---
        elif i[0] == "func":
            func_name = i[1]
            params = i[2:]
            current_index = all_commands.index(i)
            endfunc_index = find_matching_end(all_commands, current_index, "func", "endfunc")
            if endfunc_index != -1:
                functions[func_name] = (params, all_commands, current_index)
                return endfunc_index - current_index
            else:
                print("Error: Missing endfunc for function", func_name)

        elif i[0] == "call":
            func_name = i[1]
            args = [resolve_value(arg, variables) for arg in i[2:]]
            call_function(func_name, args, variables, all_commands)

        # --- CONTROL FLOW ---
        elif i[0] == "if":
            then_index = i.index("then") if "then" in i else None
            if then_index:
                condition_tokens = i[1:then_index]
                command_tokens = i[then_index + 1:]
                if evaluate_condition(condition_tokens, variables):
                    for cmd in " ".join(command_tokens).split(";"):
                        cmd_tokens = parse_line(cmd.strip())
                        execute_single_command(cmd_tokens, variables, all_commands)
        elif i[0] == "while":
            pass  # Keep old while logic here
        elif i[0] == "for":
            pass  # Keep old for logic here
        elif i[0] == "input":
            prompt = " ".join(i[2:]) if len(i) > 2 else ""
            variables[i[1]] = input(prompt)

        # Add other commands here as needed

    def find_matching_end(commands, start_index, start_keyword, end_keyword):
        depth = 1
        current_index = start_index + 1
        while current_index < len(commands) and depth > 0:
            if commands[current_index] and commands[current_index][0] == start_keyword:
                depth += 1
            elif commands[current_index] and commands[current_index][0] == end_keyword:
                depth -= 1
            current_index += 1
        return current_index - 1 if depth == 0 else -1

    def call_function(func_name, args, current_variables, all_commands, return_var=None):
        if func_name not in functions:
            print(f"Error: Function '{func_name}' not defined")
            return None
        params, body_commands, func_start_index = functions[func_name]
        local_vars = current_variables.copy()
        for param_name, arg_value in zip(params, args):
            local_vars[param_name] = arg_value
        index = func_start_index + 1
        while index < len(all_commands) and all_commands[index] and all_commands[index][0] != "endfunc":
            cmd = all_commands[index]
            if cmd[0] == "return":
                return resolve_value(cmd[1], local_vars) if len(cmd) > 1 else None
            skip_ahead = execute_single_command(cmd, local_vars, all_commands)
            if skip_ahead is not None:
                index += skip_ahead
            index += 1

    # --- PARSE LINES ---
    cleaned = [parse_line(line.strip()) for line in lines.split("\n") if line.strip()]

    # --- EXECUTE LINES ---
    index = 0
    while index < len(cleaned):
        i = cleaned[index]
        skip_ahead = execute_single_command(i, variables, cleaned)
        if skip_ahead is not None:
            index += skip_ahead
        index += 1


def main():
    """CLI entry point"""
    if len(sys.argv) < 2:
        print("Usage: python -m cerona.main <filename>")
        sys.exit(1)
    
    filename = sys.argv[1]
    try:
        with open(filename, 'r') as file:
            lines = file.read()
    except FileNotFoundError:
        print(f"File '{filename}' not found.")
        sys.exit(1)
    
    ifs(lines)


if __name__ == "__main__":
    main()
