"""Step 12: Create and start systemd service."""

from __future__ import annotations

import asyncio

from easyclaw_tui.steps.base import BaseStep, StepResult


SERVICE_TEMPLATE = """[Unit]
Description=OpenClaw Gateway (EasyClaw Foreman)
After=network.target

[Service]
Type=simple
User=root
Environment=HOME=/root
Environment=OPENROUTER_API_KEY={or_key}
{oai_env}
ExecStart=/usr/bin/openclaw gateway --bind {bind}
Restart=on-failure
RestartSec=5
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
"""


class SystemdStep(BaseStep):
    STEP_NUM = 12
    STEP_NAME = "Systemd"

    async def run(self) -> StepResult:
        oai_env = ""
        if self.state.openai_key:
            oai_env = f"Environment=OPENAI_API_KEY={self.state.openai_key}"

        service_content = SERVICE_TEMPLATE.format(
            or_key=self.state.openrouter_key,
            oai_env=oai_env,
            bind=self.state.bind,
        )

        # Write service file
        escaped = service_content.replace("'", "'\\''")
        rc, _, err = await self.run_cmd(
            f"{self.sudo('tee')} /etc/systemd/system/openclaw-gateway.service > /dev/null << 'EOSVC'\n{service_content}\nEOSVC"
        )
        if rc != 0:
            return StepResult(False, message=f"Failed to write service file: {err}")

        # Enable and start
        await self.run_cmd(self.sudo("systemctl daemon-reload"))
        await self.run_cmd(self.sudo("systemctl enable openclaw-gateway >/dev/null 2>&1"))
        await self.run_cmd(self.sudo("systemctl start openclaw-gateway"))

        await asyncio.sleep(3)

        # Check status
        if await self.cmd_ok("systemctl is-active --quiet openclaw-gateway"):
            self.ok("Gateway service running")
        else:
            self.warn("Gateway service may still be starting — check: systemctl status openclaw-gateway")

        return StepResult(True)
