"""测试 DockerRunner: 创建容器 → 安装配置 git → clone 仓库 → 清理"""

import sys
import logging

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(name)s] %(levelname)s: %(message)s")
logger = logging.getLogger("test_docker_git")


def main():
    from tool_agent.runtime.docker_runner import DockerRunner

    runner = DockerRunner(lazy_init=True)

    # ---- Step 1: 创建容器 ----
    logger.info("=" * 60)
    logger.info("Step 1: 创建容器 (ubuntu:22.04)")
    result = runner.create_container(
        tool_id="test_git_tool",
        image="ubuntu:22.04",
        mem_limit="512m",
        nano_cpus=1_000_000_000,
    )

    if "error" in result:
        logger.error(f"创建容器失败: {result['error']}")
        sys.exit(1)

    container_id = result["container_id"]
    logger.info(f"容器已创建: {container_id[:12]}")

    try:
        # ---- Step 2: 安装 git ----
        logger.info("=" * 60)
        logger.info("Step 2: 安装 git")
        res = runner.run_command(
            container_id,
            "apt-get update -qq && apt-get install -y -qq git > /dev/null 2>&1 && git --version",
            timeout=120,
        )
        if res.get("exit_code", -1) != 0:
            logger.error(f"安装 git 失败: {res}")
            sys.exit(1)
        logger.info(f"git 安装成功: {res['stdout'].strip()}")

        # ---- Step 3: 配置 git ----
        logger.info("=" * 60)
        logger.info("Step 3: 配置 git 用户")
        res = runner.run_command(
            container_id,
            'git config --global user.name "Tool Agent" && '
            'git config --global user.email "agent@tool-agent.local" && '
            'git config --global --list',
        )
        if res.get("exit_code", -1) != 0:
            logger.error(f"配置 git 失败: {res}")
            sys.exit(1)
        logger.info(f"git 配置:\n{res['stdout'].strip()}")

        # ---- Step 4: clone 仓库 ----
        logger.info("=" * 60)
        logger.info("Step 4: git clone 仓库")
        res = runner.run_command(
            container_id,
            "cd /app && git clone --depth 1 https://github.com/pallets/flask.git",
            timeout=120,
        )
        if res.get("exit_code", -1) != 0:
            logger.error(f"clone 失败: {res}")
            sys.exit(1)
        logger.info("clone 完成")

        # ---- Step 5: 验证 clone 结果 ----
        logger.info("=" * 60)
        logger.info("Step 5: 验证 clone 结果")
        res = runner.run_command(
            container_id,
            "ls -la /app/flask/ && echo '---' && cd /app/flask && git log --oneline -3",
        )
        if res.get("exit_code", -1) != 0:
            logger.error(f"验证失败: {res}")
            sys.exit(1)
        logger.info(f"仓库内容:\n{res['stdout'].strip()}")

        logger.info("=" * 60)
        logger.info("ALL TESTS PASSED!")

    finally:
        # ---- Step 6: 清理 ----
        logger.info("=" * 60)
        logger.info("Step 6: 销毁容器")
        cleanup = runner.destroy_container(container_id)
        logger.info(f"清理结果: {cleanup}")


if __name__ == "__main__":
    main()
