#!/usr/bin/env python3
"""tbot sidecar entrypoint.

Fetches tbot config from AWS Secrets Manager, writes it to disk, then execs tbot.
"""
import json
import os
import subprocess
import sys

import boto3


def main():
    region = os.environ.get("AWS_REGION", "us-west-2")
    secret_name = os.environ.get("TBOT_CONFIG_SECRET", "cube-mcp/tbot-config")
    config_path = "/tmp/tbot.yaml"

    print(f"Fetching tbot config from Secrets Manager: {secret_name}", flush=True)

    client = boto3.client("secretsmanager", region_name=region)
    try:
        resp = client.get_secret_value(SecretId=secret_name)
        config = resp["SecretString"]
    except Exception as e:
        print(f"Failed to fetch tbot config: {e}", file=sys.stderr, flush=True)
        print("tbot will not start. Phase 2 tools will be unavailable.", flush=True)
        # Sleep forever so the container doesn't restart-loop
        import time
        while True:
            time.sleep(3600)

    with open(config_path, "w") as f:
        f.write(config)

    print(f"tbot config written to {config_path}", flush=True)
    print("Starting tbot...", flush=True)

    os.execvp("tbot", ["tbot", "start", "-c", config_path])


if __name__ == "__main__":
    main()
