import shutil
import sys
import os
import time
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..'))
import core.logger as logger
from core.behavior_tree import ReleaseFlowAction, ReleaseFlowActionDecorator
from thirdparty.py_trees.common import Status, Access
from database import *
from utils.shell import shell
log = logger.get_logger()

def sync_source(repo_url, xml_path):
    """
    同步源码
    """
    # 检查xml文件是否存在
    if not os.path.exists(xml_path):
        log.error(f"XML file {xml_path} does not exist!")
        raise Exception(f"XML file {xml_path} does not exist!")
    
    # 检查是否有人修改build目录下的文件
    _, out, _ = shell(f'cd {ReleaseOptions.AlkaidRootPath}/build && git status -s')
    lines = out.strip().split('\n')
    if lines:
        warning_msg = "WARNING!!!! You MODIFY build/* files:\n"
        log.warning(warning_msg + "\n".join(lines))
    
    # 复制xml文件到.repo/manifests目录
    shutil.copy(xml_path, f"{ReleaseOptions.AlkaidRootPath}/.repo/manifests")

    # reset当前环境，根据xml文件重新拉取代码
    shell('repo forall -p -v build -c "git clean -fd && git reset --hard;"')
    shell(f'repo init -u {repo_url} -m {xml_path}')
    shell('repo forall -p -c -v build "repo sync -c --no-tags . ;"')
    
@ReleaseFlowActionDecorator
class _PhaseEnv_Process(ReleaseFlowAction):
    def setup(self):
        self.process_over = False

    def process(self):
        self.status = Status.RUNNING
        if self.process_over:
            self.status = Status.SUCCESS
            return self.status
        self.blackboard.register_key(key="test_key")
        self.blackboard.test_key = "test_value"
        # 获取参数
        repo_url = REPO_URL
        xml_path = ReleaseOptions.SnapShotXml
        
        log.info(f"Syncing source with repo_url: {repo_url}, xml_path: {xml_path}")
        
        sync_source(repo_url, xml_path)
        self.process_over = True
        self.status = Status.SUCCESS
        return self.status
    
    def update(self):
        return self.status
