from pathlib import Path
import subprocess


REPO_ROOT = Path(__file__).resolve().parents[2]
SCRIPT_PATH = REPO_ROOT / "deploy" / "deploy-to-nas-tongweb.sh"
REMOTE_DEPLOY_PATH = REPO_ROOT / "deploy" / "remote-deploy-tongweb.py"


def test_tongweb_sh_dry_run_uses_default_target():
    result = subprocess.run(
        ["bash", str(SCRIPT_PATH), "--dry-run"],
        cwd=REPO_ROOT,
        capture_output=True,
        text=True,
    )

    assert result.returncode == 0
    assert "Host: 116.62.17.81" in result.stdout
    assert "Port: 9444" in result.stdout
    assert "Username: wkc" in result.stdout
    assert "RemoteRoot: /volume1/webapp/ccdi" in result.stdout
    assert "TongWebHome: /opt/TongWeb" in result.stdout
    assert "AppName: ruoyi-admin" in result.stdout


def test_tongweb_sh_dry_run_accepts_override_arguments():
    result = subprocess.run(
        [
            "bash",
            str(SCRIPT_PATH),
            "10.0.0.8",
            "2222",
            "deploy-user",
            "secret",
            "/volume2/custom/app",
            "/data/TongWeb7",
            "ccdi-console",
            "--dry-run",
        ],
        cwd=REPO_ROOT,
        capture_output=True,
        text=True,
    )

    assert result.returncode == 0
    assert "Host: 10.0.0.8" in result.stdout
    assert "Port: 2222" in result.stdout
    assert "Username: deploy-user" in result.stdout
    assert "RemoteRoot: /volume2/custom/app" in result.stdout
    assert "TongWebHome: /data/TongWeb7" in result.stdout
    assert "AppName: ccdi-console" in result.stdout


def test_tongweb_sh_script_should_call_remote_deploy_helper():
    script_text = SCRIPT_PATH.read_text(encoding="utf-8")

    assert 'remote-deploy-tongweb.py' in script_text
    assert 'ruoyi-admin/target/ruoyi-admin.war' in script_text


def test_remote_deploy_tongweb_should_use_autodeploy_and_tongweb_scripts():
    script_text = REMOTE_DEPLOY_PATH.read_text(encoding="utf-8")

    assert "autodeploy" in script_text
    assert "startservernohup.sh" in script_text
    assert "stopserver.sh" in script_text
