"""Step 15: Health checks and summary."""

from __future__ import annotations

import asyncio
from datetime import datetime, timezone

from easyclaw_tui.steps.base import BaseStep, StepResult


class HealthStep(BaseStep):
    STEP_NUM = 15
    STEP_NAME = "Health"

    async def run(self) -> StepResult:
        await asyncio.sleep(2)

        # Gateway health
        rc, out, _ = await self.run_cmd("openclaw health 2>/dev/null")
        if any(w in out.lower() for w in ("ok", "healthy", "running")):
            self.ok("Gateway: healthy")
        else:
            self.warn("Gateway health check inconclusive — may need more time")

        # MCP test
        rc, out, _ = await self.run_cmd(
            'mcporter call easyclaw.search_knowledge query="gateway setup" 2>/dev/null'
        )
        if any(w in out.lower() for w in ("gateway", "openclaw")):
            self.ok("EasyClaw MCP: tools working")
        else:
            self.warn("MCP tool test inconclusive — check: mcporter call easyclaw.search_knowledge query=\"test\"")

        # Doctor
        self.info("Running openclaw doctor...")
        _, doc_out, _ = await self.run_cmd("openclaw doctor 2>&1 | head -15 || true")
        if doc_out:
            for line in doc_out.split("\n")[:10]:
                self.panel.log_raw(f"  {line}")

        # Write summary
        await self._write_summary()

        # Final output
        self.panel.log_raw("")
        self.panel.log_raw("[bold green]╔═══════════════════════════════════════════════════════╗[/bold green]")
        self.panel.log_raw("[bold green]║         Installation Complete!                        ║[/bold green]")
        self.panel.log_raw("[bold green]╚═══════════════════════════════════════════════════════╝[/bold green]")
        self.panel.log_raw("")
        self.panel.log_raw(f"  [bold]Model:[/bold]    {self.state.model}")
        self.panel.log_raw(f"  [bold]Bind:[/bold]     {self.state.bind}")
        self.panel.log_raw(f"  [bold]Channel:[/bold]  {self.state.channel}")
        self.panel.log_raw(f"  [bold]MCP:[/bold]      EasyClaw connected")
        self.panel.log_raw(f"  [bold]Service:[/bold]  openclaw-gateway (systemd)")
        self.panel.log_raw("")
        self.panel.log_raw("  [cyan]Summary saved to: ~/.openclaw/install-summary.txt[/cyan]")
        self.panel.log_raw("")
        self.panel.log_raw("  [bold]Test your agent:[/bold]")
        self.panel.log_raw('    openclaw agent -m "Hello, what tools do you have?" --agent main')
        self.panel.log_raw("")
        self.panel.log_raw("  [bold]Dashboard:[/bold] https://easyclaw.help/dashboard.html")
        self.panel.log_raw("")
        self.panel.log_raw("  [yellow]Need help? Press F1 to chat with the Foreman[/yellow]")

        return StepResult(True)

    async def _write_summary(self) -> None:
        """Write install summary to ~/.openclaw/install-summary.txt."""
        now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
        masked_or = ""
        if self.state.openrouter_key:
            k = self.state.openrouter_key
            masked_or = f"{k[:12]}...{k[-4:]}"
        masked_ec = ""
        if self.state.api_key:
            k = self.state.api_key
            masked_ec = f"{k[:12]}...{k[-4:]}"

        summary = f"""# EasyClaw Foreman — Installation Summary
# Generated: {now}

## Configuration
- Model: {self.state.model} ({self.state.model_path})
- Fallback: {self.state.fallback_path}
- Bind: {self.state.bind}
- Channel: {self.state.channel}
- Memory search: {self.state.memory_enabled}

## Credentials
- EasyClaw API key: {masked_ec}
- OpenRouter key: {masked_or}
- Gateway token: {self.state.gateway_token}

## File Locations
- Config: ~/.openclaw/openclaw.json
- Workspace: ~/.openclaw/workspace/
- MCP config: ~/.mcporter/mcporter.json
- Service: /etc/systemd/system/openclaw-gateway.service
- This summary: ~/.openclaw/install-summary.txt

## Useful Commands
- systemctl status openclaw-gateway    # Service status
- journalctl -u openclaw-gateway -f    # Tail logs
- systemctl restart openclaw-gateway   # Restart after changes
- openclaw health                      # Gateway health
- openclaw doctor                      # Full diagnostics
- openclaw config validate             # Check config
- mcporter list easyclaw --schema      # MCP tools
"""
        escaped = summary.replace("'", "'\\''")
        await self.run_cmd(f"cat > ~/.openclaw/install-summary.txt << 'EOSUMMARY'\n{summary}\nEOSUMMARY")
