"""vigilis — health monitoring + system health.

Tools:
  vigilis_check_sleep     — get today's/this week's sleep summary from Oura
  vigilis_check_readiness — today's readiness score + exercise recommendation
  vigilis_check_system    — lucerna status, budget, hook health
  vigilis_log_symptom     — append a symptom entry to vault health log
"""

import datetime
import os
import subprocess

from vivesca.base import run_cli
from vivesca.schemas import ActionOutput, StatusOutput, ToolOutput

from fastmcp.tools import tool
from mcp.types import ToolAnnotations

SOPOR = "sopor"
HEALTH_LOG = os.path.expanduser("~/notes/Health/Symptom Log.md")


class SleepResult(ToolOutput):
    """Sleep data from Oura."""
    summary: str


class ReadinessResult(ToolOutput):
    """Readiness score with exercise guidance."""
    summary: str
    guidance: str


class SystemHealthResult(ToolOutput):
    """System health check results."""
    sections: list[str]


@tool(
    name="vigilis_check_sleep",
    description="Oura sleep data. 'today' for last night, 'week' for trend.",
    annotations=ToolAnnotations(readOnlyHint=True, destructiveHint=False),
)
def vigilis_check_sleep(period: str = "today") -> SleepResult:
    """Check sleep data."""
    result = run_cli(SOPOR, [period], timeout=15)
    return SleepResult(summary=result)


@tool(
    name="vigilis_check_readiness",
    description="Oura readiness + exercise recommendation.",
    annotations=ToolAnnotations(readOnlyHint=True, destructiveHint=False),
)
def vigilis_check_readiness() -> ReadinessResult:
    """Check readiness and recommend exercise intensity."""
    raw = run_cli(SOPOR, ["today"], timeout=15)
    guidance = (
        "Exercise guidance: check readiness score above.\n"
        "- <70: light only (walk, gentle stretch)\n"
        "- 70-75: moderate OK (yoga, light weights)\n"
        "- >75: full intensity cleared"
    )
    return ReadinessResult(summary=raw, guidance=guidance)


@tool(
    name="vigilis_check_system",
    description="System health: lucerna, budget, recent copia events.",
    annotations=ToolAnnotations(readOnlyHint=True, destructiveHint=False),
)
def vigilis_check_system() -> SystemHealthResult:
    """Check lucerna + copia system health."""
    parts = []

    try:
        result = subprocess.run(
            ["launchctl", "list"],
            capture_output=True, text=True, timeout=5,
        )
        lucerna_lines = [
            ln for ln in result.stdout.splitlines() if "lucerna" in ln
        ]
        parts.append("Lucerna: " + ("; ".join(lucerna_lines) or "NOT FOUND"))
    except Exception as e:
        parts.append(f"Lucerna: check failed ({e})")

    try:
        budget = run_cli("usus", ["--json"], timeout=15)
        parts.append(f"Budget: {budget}")
    except Exception:
        parts.append("Budget: usus unavailable")

    log = os.path.expanduser("~/logs/copia-events.jsonl")
    try:
        with open(log) as f:
            lines = f.readlines()
        tail = lines[-5:] if len(lines) >= 5 else lines
        parts.append("Recent events:\n" + "".join(tail))
    except Exception:
        parts.append("Events: log not found")

    return SystemHealthResult(sections=parts)


@tool(
    name="vigilis_log_symptom",
    description="Log a symptom to vault health log.",
    annotations=ToolAnnotations(readOnlyHint=False, destructiveHint=False),
)
def vigilis_log_symptom(symptom: str, severity: str = "mild", notes: str = "") -> ActionOutput:
    """Log a symptom to the vault."""
    today = datetime.date.today().isoformat()
    entry = f"\n## {today} — {symptom}\n- Severity: {severity}\n"
    if notes:
        entry += f"- Notes: {notes}\n"

    os.makedirs(os.path.dirname(HEALTH_LOG), exist_ok=True)
    with open(HEALTH_LOG, "a") as f:
        f.write(entry)

    return ActionOutput(success=True, message=f"Logged: {symptom} ({severity}) on {today}")
