"""Placeholder MCP tools for the action framework.

All actions are log-only — no actual execution until connectors are built.
"""

from __future__ import annotations

import json
import logging
from datetime import datetime, timezone
from pathlib import Path

from common.actions.config import ActionSettings

logger = logging.getLogger(__name__)

_settings: ActionSettings | None = None


def _get_settings() -> ActionSettings:
    global _settings
    if _settings is None:
        _settings = ActionSettings()
    return _settings


def _append_audit_log(entry: dict) -> None:
    """Append an entry to the JSONL audit log."""
    settings = _get_settings()
    path = settings.audit_log_path
    path.parent.mkdir(parents=True, exist_ok=True)
    with open(path, "a", encoding="utf-8") as f:
        f.write(json.dumps(entry, default=str) + "\n")


def _read_audit_log(limit: int = 20) -> list[dict]:
    """Read the most recent entries from the audit log."""
    settings = _get_settings()
    path = settings.audit_log_path
    if not path.exists():
        return []
    lines = path.read_text(encoding="utf-8").strip().splitlines()
    entries = []
    for line in lines[-limit:]:
        try:
            entries.append(json.loads(line))
        except json.JSONDecodeError:
            continue
    return entries


AVAILABLE_ACTIONS = [
    {"name": "restart_component", "description": "Restart a service/deployment", "status": "placeholder"},
    {"name": "create_issue", "description": "Create GitLab/GitHub issue", "status": "placeholder"},
    {"name": "send_alert", "description": "Send alert to Slack/Teams/webhook", "status": "placeholder"},
    {"name": "scale_deployment", "description": "Scale a deployment up/down", "status": "placeholder"},
    {"name": "add_comment", "description": "Add comment to existing issue", "status": "placeholder"},
    {"name": "run_pipeline", "description": "Trigger CI/CD pipeline", "status": "placeholder"},
    {"name": "rollback_deployment", "description": "Rollback to previous deployment version", "status": "placeholder"},
]


def register_action_tools(mcp_server) -> None:
    """Register action MCP tools on the given MCP server."""

    @mcp_server.tool()
    def execute_action(action_name: str, params: dict | None = None, dry_run: bool = True) -> dict:
        """Execute an action (placeholder — logs only, no actual execution).

        Actions: restart_component, create_issue, send_alert, scale_deployment,
        add_comment, run_pipeline, rollback_deployment.
        """
        params = params or {}
        entry = {
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "action": action_name,
            "params": params,
            "dry_run": dry_run,
            "status": "logged",
        }
        _append_audit_log(entry)
        logger.info("ACTION_REQUEST: %s", entry)
        return {
            "status": "logged",
            "message": f"Action '{action_name}' logged (not executed — placeholder)",
            "entry": entry,
        }

    @mcp_server.tool()
    def list_available_actions() -> list[dict]:
        """List all available actions the agent can request."""
        return AVAILABLE_ACTIONS

    @mcp_server.tool()
    def get_action_log(limit: int = 20) -> list[dict]:
        """Retrieve recent action requests from the audit log."""
        return _read_audit_log(limit)
