#!/usr/bin/env python3
# -*- coding:utf-8 -*-
from inc import CliTool
import sys, os, datetime
import subprocess
from typing import Optional

isIntra = (sys.argv[2] == 'intra')
env = sys.argv[3]
mode = sys.argv[4]

app = 'node-video-v2'
module = 'www/' + app

fileName =  '/hosts-honor-ykt.txt'
filePath = os.path.dirname(sys.argv[0]) + fileName

ipsMap = CliTool.getIpsMap(filePath, isIntra, 8873, module)
envList = CliTool.getEnvList(env, ipsMap, isIntra)

ips = {}
for env in envList:
    ips = dict(ips, **ipsMap[env])

def checkDistPath(distPath):
    ##check dist is empty
    print(os.path.exists(distPath))
    if os.path.exists(distPath) is False:
        print("{} does not exist".format(distPath))
        return False

    if len(os.listdir(distPath)) == 0:
        print("Folder {} is empty".format(distPath))
        return False
    
    return True 

def get_nvm_path() -> Optional[str]:
    """
    从 .bashrc 文件中获取 NVM 路径
    
    Returns:
        NVM 路径或 None（如果未找到）
    """
    bashrc_path = os.path.expanduser("~/.bashrc")
    
    if not os.path.exists(bashrc_path):
        return None
    
    try:
        nvm_dir = None
        
        with open(bashrc_path, 'r', encoding='utf-8') as f:
            content = f.read()
            
            # 查找 NVM_DIR 环境变量设置
            for line in content.split('\n'):
                line = line.strip()
                if line.startswith('export NVM_DIR='):
                    # 提取引号内的值
                    nvm_dir_value = line.split('=', 1)[1].strip('\'"')
                    
                    # 处理 $HOME 变量
                    if nvm_dir_value.startswith('$HOME'):
                        nvm_dir = nvm_dir_value.replace('$HOME', os.path.expanduser('~'))
                    else:
                        nvm_dir = os.path.expanduser(nvm_dir_value)
                    
                    break
            
            # 如果找到了 NVM_DIR，检查 nvm.sh 是否存在
            if nvm_dir:
                nvm_sh_path = os.path.join(nvm_dir, 'nvm.sh')
                if os.path.exists(nvm_sh_path):
                    return nvm_sh_path
                else:
                    print(f"NVM_DIR 已设置为 {nvm_dir}，但 nvm.sh 文件不存在")
            
            # 备用方案：直接查找 source nvm.sh 的行
            for line in content.split('\n'):
                line = line.strip()
                if ('source' in line or '\\.' in line) and 'nvm.sh' in line:
                    # 处理类似 [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" 的格式
                    if '$NVM_DIR' in line and nvm_dir:
                        nvm_sh_path = os.path.join(nvm_dir, 'nvm.sh')
                        if os.path.exists(nvm_sh_path):
                            return nvm_sh_path
                    
                    # 处理直接路径
                    import re
                    match = re.search(r'["\']([^"\']*nvm\.sh)["\']', line)
                    if match:
                        nvm_path = match.group(1)
                        nvm_path = nvm_path.replace('$NVM_DIR', nvm_dir if nvm_dir else '')
                        nvm_path = os.path.expanduser(nvm_path)
                        if os.path.exists(nvm_path):
                            return nvm_path
                            
    except Exception as e:
        print(f"读取 .bashrc 时发生错误: {e}")
    
    return None


def exec_command(cmd: str, output_resp: bool = False) -> str:
    """
    执行bash命令并返回输出结果
    
    Args:
        cmd: 要执行的命令
        output_resp: 是否实时打印输出
    
    Returns:
        命令的输出结果
        
    Raises:
        subprocess.CalledProcessError: 命令执行失败时抛出
    """
    # 获取 NVM 路径
    nvm_path = get_nvm_path()
    if not nvm_path:
        # 如果在 .bashrc 中找不到，尝试默认路径
        default_nvm_path = os.path.expanduser("~/.nvm/nvm.sh")
        if os.path.exists(default_nvm_path):
            nvm_path = default_nvm_path
        else:
            raise FileNotFoundError("无法找到 NVM 安装路径，请检查 .bashrc 配置")
    
    output_str = ''
    command = f"source {nvm_path} && {cmd}"
    
    try:
        with subprocess.Popen(
            ['/bin/bash', '-c', command],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            universal_newlines=True,
            bufsize=1
        ) as process:
            
            # 实时读取输出
            for line in process.stdout:
                line = line.strip()
                if line:
                    if output_resp:
                        print(line)
                    else:
                        output_str += line + '\n'
            
            # 等待进程结束并检查返回码
            return_code = process.wait()
            if return_code != 0:
                raise subprocess.CalledProcessError(return_code, command)
                
    except subprocess.CalledProcessError as e:
        print(f"命令执行失败: {e}")
        raise
    except Exception as e:
        print(f"执行命令时发生错误: {e}")
        raise
    
    return output_str.strip()

## check nvm version
nvmVersion = exec_command('nvm -v')
if '0.39' not in nvmVersion:
    print("NVM 未安装，请先安装nvm")
    exit()

## check node -version
nodeVersion = 'v16.19.1'
checkResp = exec_command(f"nvm ls {nodeVersion}")
if 'N/A' in checkResp:
    print("Node.js {} is not installed. Please install it using NVM and try again.".format(nodeVersion))
    exit()

exclude_ext = ' --include=/dist/  --exclude=/* '
localPwdFile = '/Users/tangjianhui/Documents/publish/tjds1.passwd'

##node api path
localSrc =  CliTool.workspace()  + app + '.git/'

##apicmd
apicmd = "export PUPPETEER_SKIP_DOWNLOAD=true; cd {} && nvm use {} && yarn && yarn build".format(localSrc, nodeVersion)

print("start run command " + apicmd)
exec_command(apicmd, True)
exec_command('cd ' + localSrc + ' && cp pm2.json ./dist/', True)

#check dist is empty
distPath = localSrc + 'dist/'
if checkDistPath(distPath) is False:
    exit()

cmdTpl = 'rsync -%s --delay-updates --del --stats --port=%s --password-file=' + localPwdFile + ' --timeout=120 ' + CliTool.excludeFile() + exclude_ext + localSrc + ' www@%s::%s/'

Ct = CliTool()
Ct.publish(ips, mode, cmdTpl)
