"""TelemetryService - System metrics collection for TUI.

Contract: CNT-TUI-SVC-001
Traceability: UX-001
"""

import time
from dataclasses import dataclass

import psutil


@dataclass(frozen=True)
class TelemetryData:
    """Snapshot of telemetry metrics."""

    session_elapsed_seconds: float
    task_elapsed_seconds: float | None
    last_result: str
    memory_mb: int
    cpu_percent: float


class TelemetryService:
    """Service for collecting system and session metrics.

    Responsibilities:
    - Track session duration
    - Track current task duration
    - Record last execution result
    - Collect memory/CPU metrics

    This service is TUI-specific and does NOT modify existing services.
    """

    def __init__(self) -> None:
        """Initialize with session start time."""
        self._session_start = time.time()
        self._task_start: float | None = None
        self._last_result = "--"

    def start_task(self) -> None:
        """Mark the start of a task execution."""
        self._task_start = time.time()

    def end_task(self, success: bool, phase: int, step: int) -> None:
        """Mark the end of a task execution.

        Args:
            success: Whether the task succeeded
            phase: Phase number that was executed
            step: Step number that was executed
        """
        status = "✔" if success else "✘"
        self._last_result = f"{status} P{phase}-S{step}"
        self._task_start = None

    def reset_task(self) -> None:
        """Clear task timer without recording result."""
        self._task_start = None

    def get_data(self) -> TelemetryData:
        """Get current telemetry snapshot.

        Returns:
            TelemetryData with current metrics
        """
        now = time.time()
        process = psutil.Process()

        task_elapsed: float | None = None
        if self._task_start is not None:
            task_elapsed = now - self._task_start

        return TelemetryData(
            session_elapsed_seconds=now - self._session_start,
            task_elapsed_seconds=task_elapsed,
            last_result=self._last_result,
            memory_mb=process.memory_info().rss // (1024 * 1024),
            cpu_percent=process.cpu_percent(interval=None),
        )

    @staticmethod
    def format_duration(seconds: float) -> str:
        """Format seconds as HH:MM:SS.

        Args:
            seconds: Duration in seconds

        Returns:
            Formatted string
        """
        hours, remainder = divmod(int(seconds), 3600)
        minutes, secs = divmod(remainder, 60)
        return f"{hours:02d}:{minutes:02d}:{secs:02d}"

    @staticmethod
    def format_task_time(seconds: float | None) -> str:
        """Format task time as MM:SS or placeholder.

        Args:
            seconds: Duration in seconds or None

        Returns:
            Formatted string or placeholder
        """
        if seconds is None:
            return "--:--"
        minutes, secs = divmod(int(seconds), 60)
        return f"{minutes:02d}:{secs:02d}"
