from tools.ToolBase import ToolBase
import re
import os
import shlex
import subprocess
import tempfile
import pexpect

class OtherTool(ToolBase):
    def validate_instruction(self, instruction):
        #指令过滤
        timeout = 60*2
        return instruction,timeout

    def do_worker_script(self,str_instruction,timeout,ext_params):
        # 创建临时文件保存输出
        with tempfile.NamedTemporaryFile(delete=False) as tmpfile:
            output_file = tmpfile.name

        # 使用 shlex.quote 对 str_instruction 进行安全包装,确保整个命令作为一个参数传递
        safe_instr = shlex.quote(str_instruction.strip())
        # 构建 script 命令
        # 注意:此时 safe_instr 包含单引号,确保整个 -c 参数不被拆分
        script_cmd = f"script -q -c {safe_instr} {output_file}"
        # 选项 -q 表示静默(quiet),减少不必要的输出

        # # 构建并执行 script 命令
        # script_cmd = f"script -c '{str_instruction}' {output_file}"
        try:
            result = subprocess.run(script_cmd, shell=True, text=True,timeout=timeout)
            # 读取输出文件内容
            with open(output_file, 'r') as f:
                output = f.read()
                lines = output.splitlines()
                # 跳过第一行(Script started)和最后一行(Script done)
                ftp_output = lines[1:-1]
                output = '\n'.join(ftp_output)
        except subprocess.TimeoutExpired:
            output = "命令超时返回"
            try:
                with open(output_file, 'r') as f:
                    partial_output = f.read()
                if partial_output:
                    output += f"\n部分输出:\n{partial_output}"
            except FileNotFoundError:
                pass  # 文件可能未创建
        except subprocess.CalledProcessError as e:
            output = f"错误: {e}"
        finally:
            # 删除临时文件
            try:
                os.remove(output_file)
            except FileNotFoundError:
                pass  # 文件可能未创建
        return output

    def do_worker_pexpect(self, str_instruction, timeout, ext_params):
        try:
            result = ""
            exc_do = pexpect.spawn('bash', ['-c', str_instruction], timeout=timeout,
                                   encoding='utf-8')  # spawn 第一个参数是可执行文件
            index = exc_do.expect([
                pexpect.TIMEOUT,
                pexpect.EOF
            ])
            result += str(exc_do.before)
            if index == 0:
                result += f"\n执行超时{timeout}秒"
            elif index == 1:
                pass
            else:
                print("遇到其他输出!")
                pass
            return result
        except Exception as e:
            return f"执行错误: {str(e)}"

    def execute_instruction(self, instruction_old):
        ext_params = self.create_extparams()
        # 第一步:验证指令合法性
        instruction,time_out = self.validate_instruction(instruction_old)
        if not instruction:
            return False, instruction_old, "该指令暂不执行!","",ext_params
        # 过滤修改后的指令是否需要判重?同样指令再执行结果一致?待定---#?

        # 第二步:执行指令---需要对ftp指令进行区分判断
        #output = self.do_worker_script(instruction, time_out, ext_params)
        output = self.do_worker_pexpect(instruction, time_out, ext_params)

        # 第三步:分析执行结果
        analysis = self.analyze_result(output,instruction,"","")

        return True, instruction, analysis,output,ext_params

    def analyze_result(self, result,instruction,stderr,stdout):
        #指令结果分析
        return result