"""Session manager with system prompt drift detection."""
from __future__ import annotations

import hashlib
import uuid
from datetime import datetime, timezone
from typing import Optional

from .findings import RuntimeFinding


def _generate_session_id() -> str:
    return "sess_" + uuid.uuid4().hex[:12]


class SessionManager:
    def __init__(self, session_id: Optional[str] = None) -> None:
        self.session_id = session_id or _generate_session_id()
        self._system_prompt_hash: Optional[str] = None
        self._message_count = 0
        self._tool_call_count = 0
        self._findings_count = 0
        self._started_at = datetime.now(timezone.utc).isoformat()

    def record_system_prompt(self, content: str) -> Optional[RuntimeFinding]:
        """Hash system prompt. Return SYSTEM_PROMPT_DRIFT finding if it changes."""
        h = hashlib.sha256(content.encode("utf-8")).hexdigest()
        if self._system_prompt_hash is None:
            self._system_prompt_hash = h
            return None
        if h != self._system_prompt_hash:
            self._system_prompt_hash = h
            return RuntimeFinding(
                session_id=self.session_id,
                severity="high",
                category="SYSTEM_PROMPT_DRIFT",
                title="System prompt changed mid-session",
                description=(
                    "The system prompt hash changed between calls. This may indicate "
                    "an attack modifying agent instructions at runtime."
                ),
                source="session",
                confidence=0.98,
                context={"detail": "Hash mismatch detected — content not logged"},
            )
        return None

    def increment_messages(self) -> None:
        self._message_count += 1

    def increment_tool_calls(self) -> None:
        self._tool_call_count += 1

    def increment_findings(self, count: int) -> None:
        self._findings_count += count

    def get_stats(self) -> dict:
        return {
            "session_id": self.session_id,
            "message_count": self._message_count,
            "tool_call_count": self._tool_call_count,
            "findings_count": self._findings_count,
            "started_at": self._started_at,
        }
