#!/usr/bin/env python3
"""Deploy delegation script - Command type."""

import shlex
import subprocess
import sys
import tomllib
from pathlib import Path

from ...utils import detect_environment, expand_variables


def main() -> int:
    """Execute custom deploy command."""
    project_root = Path.cwd()
    config_path = project_root / ".fwauto" / "config.toml"

    if not config_path.exists():
        print(f"❌ Config not found: {config_path}", file=sys.stderr)
        return 1

    with open(config_path, "rb") as f:
        config = tomllib.load(f)

    command = config.get("deploy", {}).get("command")
    if not command:
        print("❌ deploy.command not configured", file=sys.stderr)
        return 1

    # 偵測環境並展開變數
    env_vars = detect_environment()
    expanded_command = expand_variables(command, env_vars)

    if expanded_command != command:
        print(f"🔍 Detected environment: {env_vars}")
        print(f"📝 Original command: {command}")
        print(f"📝 Expanded command: {expanded_command}")

    cmd = shlex.split(expanded_command)
    print(f"📦 Running: {expanded_command}")

    result = subprocess.run(cmd, cwd=project_root)
    return result.returncode


if __name__ == "__main__":
    sys.exit(main())
