from __future__ import annotations

from pathlib import Path
import os
import subprocess


def _run_script_prefix(
    tmp_path: Path,
    relative_script_path: str,
    env_file_content: str,
    env: dict[str, str],
    output_vars: list[str],
) -> subprocess.CompletedProcess[str]:
    project_dir = tmp_path / "project"
    script_source = Path(__file__).resolve().parents[2] / relative_script_path
    script_copy = project_dir / relative_script_path
    script_copy.parent.mkdir(parents=True, exist_ok=True)
    script_copy.write_text(script_source.read_text(encoding="utf-8"), encoding="utf-8")
    (project_dir / ".env").write_text(env_file_content, encoding="utf-8")

    script_prefix = script_copy.read_text(encoding="utf-8").split('case "$MODE" in', 1)[0]
    print_lines = "\n".join(f'printf "{name}=%s\\n" "${{{name}:-}}"' for name in output_vars)
    command = f"""{script_prefix}
{print_lines}
"""

    return subprocess.run(
        ["bash", "-c", command, str(script_copy)],
        capture_output=True,
        text=True,
        env={**os.environ, **env, "MODE": "test"},
        cwd=script_copy.parent,
        check=False,
    )


def test_server_start_can_prefer_env_file_over_inherited_onlyoffice_values(tmp_path: Path) -> None:
    result = _run_script_prefix(
        tmp_path,
        "server/server_start.sh",
        env_file_content=(
            "ONLYOFFICE_ENABLED=true\n"
            "ONLYOFFICE_PUBLIC_URL=http://10.10.10.122:8082\n"
            "ONLYOFFICE_BACKEND_URL=http://main:8000\n"
            "ONLYOFFICE_JWT_SECRET=change-me-onlyoffice\n"
        ),
        env={
            "ONLYOFFICE_ENABLED": "false",
            "ONLYOFFICE_PUBLIC_URL": "http://127.0.0.1:8082",
            "X_FINANCIAL_PREFER_ENV_FILE": "true",
        },
        output_vars=["ONLYOFFICE_ENABLED", "ONLYOFFICE_PUBLIC_URL"],
    )

    assert result.returncode == 0, result.stderr
    assert "ONLYOFFICE_ENABLED=true" in result.stdout
    assert "ONLYOFFICE_PUBLIC_URL=http://10.10.10.122:8082" in result.stdout


def test_root_start_can_prefer_env_file_over_inherited_onlyoffice_values(tmp_path: Path) -> None:
    result = _run_script_prefix(
        tmp_path,
        "start.sh",
        env_file_content=(
            "ONLYOFFICE_ENABLED=true\n"
            "ONLYOFFICE_PUBLIC_URL=http://10.10.10.122:8082\n"
            "ONLYOFFICE_BACKEND_URL=http://main:8000\n"
            "ONLYOFFICE_JWT_SECRET=change-me-onlyoffice\n"
        ),
        env={
            "ONLYOFFICE_ENABLED": "false",
            "ONLYOFFICE_PUBLIC_URL": "http://127.0.0.1:8082",
            "X_FINANCIAL_PREFER_ENV_FILE": "true",
        },
        output_vars=["ONLYOFFICE_ENABLED", "ONLYOFFICE_PUBLIC_URL"],
    )

    assert result.returncode == 0, result.stderr
    assert "ONLYOFFICE_ENABLED=true" in result.stdout
    assert "ONLYOFFICE_PUBLIC_URL=http://10.10.10.122:8082" in result.stdout
