#!/usr/bin/env python3
"""Smoke test: verify Daytona API key works and can create/destroy a sandbox.

Usage (from repo root):
    cd packages/pipeline && uv run python tests/test_daytona_smoke.py
"""

import asyncio
import os
import sys
from pathlib import Path


def _load_dotenv():
    """Load .env from repo root (same file .gemini/.env symlinks to)."""
    env_path = Path(__file__).resolve().parent.parent.parent.parent / ".env"
    if not env_path.exists():
        return
    for line in env_path.read_text().splitlines():
        line = line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, _, value = line.partition("=")
        os.environ.setdefault(key.strip(), value.strip())


async def main():
    _load_dotenv()

    api_key = os.environ.get("DAYTONA_API_KEY")
    api_url = os.environ.get("DAYTONA_API_URL", "https://app.daytona.io/api")

    if not api_key:
        print("DAYTONA_API_KEY not set. Add it to .env (see .env.example).")
        sys.exit(1)

    print(f"API URL: {api_url}")
    print(f"API key: {api_key[:8]}...{api_key[-4:]}")

    from daytona import AsyncDaytona, CreateSandboxFromImageParams, Image

    client = AsyncDaytona()
    try:
        # Create a minimal sandbox
        print("\nCreating sandbox (alpine:3.20)...")
        sandbox = await client.create(
            CreateSandboxFromImageParams(image=Image.base("alpine:3.20")),
            timeout=120,
        )
        print(f"  Sandbox ID: {sandbox.id}")

        # Run a command
        response = await sandbox.process.code_run('print("hello from daytona")')
        print(f"  Code output: {response.result.strip()}")

        # Exec a shell command
        result = await sandbox.process.exec("uname -a")
        print(f"  uname: {result.result.strip()}")

        # Cleanup
        print("  Deleting sandbox...")
        await sandbox.delete()
        print("\nDaytona is working.")

    finally:
        await client.close()


if __name__ == "__main__":
    asyncio.run(main())
