# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========

# Create a sandbox from the mirage-fuse snapshot, provision the
# in-sandbox workspace (S3 FUSE-mounted at /data, the same prefix the
# host workspace uses), and print the sandbox id. The sandbox is
# yours: mirage only connects to it, so delete it when done
# (`daytona sandbox delete <id>` or the dashboard). The lifecycle
# knobs below are the safety net for a forgotten demo box.

import asyncio
import os
import sys
from typing import Any

from daytona import AsyncDaytona, CreateSandboxFromSnapshotParams
from dotenv import load_dotenv

load_dotenv(".env.development")

SNAPSHOT_NAME = "mirage-fuse"

# The sandbox-side workspace config: same mount, same prefix as
# daytona_workspace.yaml, FUSE-mounted at its own prefix so host and
# sandbox paths mean the same thing.
WORKSPACE_YAML = """\
mounts:
  /data:
    resource: s3
    config:
      bucket: {bucket}
      region: {region}
      aws_access_key_id: {key_id}
      aws_secret_access_key: {secret}
      key_prefix: mirage-daytona-cli-demo
    fuse: /data
"""


async def provision(sandbox: Any) -> None:
    config = WORKSPACE_YAML.format(bucket=os.environ["AWS_S3_BUCKET"],
                                   region=os.environ.get(
                                       "AWS_DEFAULT_REGION", "us-east-1"),
                                   key_id=os.environ["AWS_ACCESS_KEY_ID"],
                                   secret=os.environ["AWS_SECRET_ACCESS_KEY"])
    await sandbox.fs.upload_file(config.encode(), "/tmp/sandbox.yaml")
    commands = (
        "sudo mkdir -p /data && sudo chown daytona /data",
        "mirage workspace create /tmp/sandbox.yaml",
    )
    for command in commands:
        response = await sandbox.process.exec(command)
        if int(response.exit_code) != 0:
            raise RuntimeError(
                f"provisioning failed ({command}): {response.result}")
    print("provisioned: S3 FUSE-mounted at /data in the sandbox",
          file=sys.stderr)


async def main() -> None:
    client = AsyncDaytona()
    try:
        sandbox = await client.create(
            CreateSandboxFromSnapshotParams(
                snapshot=SNAPSHOT_NAME,
                auto_stop_interval=10,
                auto_delete_interval=30,
            ))
        await provision(sandbox)
        print(sandbox.id)
    finally:
        await client.close()


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