from .ext import telegram
import sys
import os
import importlib.util
import re

__all__ = ["telegram"]

def main():
    if len(sys.argv) > 1:
        command = sys.argv[1]
        
        if command.startswith('run:'):
            filename = command[4:]
            run_bot_file(filename)
        else:
            print("Usage: mehta run:<filename>")
    else:
        print("Usage: mehta run:<filename>")

def run_bot_file(filename):
    try:
        if not filename.endswith('.py'):
            filename += '.py'
        
        if not os.path.exists(filename):
            print(f"Error: File with {filename} not found")
            return
        
        with open(filename, 'r') as f:
            content = f.read()
        
        token_match = re.search(r'bot\.run\(["\']([^"\']+)["\']\)', content)
        
        if token_match:
            token = token_match.group(1)
            spec = importlib.util.spec_from_file_location("bot_module", filename)
            module = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(module)
            
            if hasattr(module, 'bot') and isinstance(module.bot, telegram):
                module.bot.run(token)
            else:
                print("Error: No bot instance found in file")
        else:
            print("Error: No bot token found in file")
                
    except Exception as e:
        print(f"Error: {e}")