"""Session data models — dataclasses for session lifecycle."""

from __future__ import annotations

from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from nestdx.tracking.cost import TokenUsage


class SessionStatus(str, Enum):
    ACTIVE = "active"
    COMPLETED = "completed"
    ABORTED = "aborted"


@dataclass
class GitSnapshot:
    head_sha: str
    branch: str
    dirty_files: list[str] = field(default_factory=list)


@dataclass
class FileChange:
    path: str
    change_type: str  # added | modified | deleted | renamed
    additions: int = 0
    deletions: int = 0


@dataclass
class ToolRun:
    tool: str
    command: str
    start_time: datetime
    end_time: datetime | None = None
    exit_code: int | None = None


@dataclass
class PolicyViolation:
    rule: str
    severity: str  # "error" | "warning"
    message: str
    file: str | None = None
    line: int | None = None
    pattern: str | None = None


@dataclass
class Session:
    id: str
    status: SessionStatus
    start_time: datetime
    end_time: datetime | None = None
    git_snapshot: GitSnapshot | None = None
    tool_runs: list[ToolRun] = field(default_factory=list)
    file_changes: list[FileChange] = field(default_factory=list)
    violations: list[PolicyViolation] = field(default_factory=list)
    config_hash: str | None = None
    token_usage: list[TokenUsage] = field(default_factory=list)

    @property
    def duration_seconds(self) -> float | None:
        if self.end_time:
            return (self.end_time - self.start_time).total_seconds()
        return None

    @property
    def has_violations(self) -> bool:
        return any(v.severity == "error" for v in self.violations)

    @property
    def total_cost(self) -> float:
        """Sum of estimated_cost_usd from all token usage entries."""
        return sum(tu.estimated_cost_usd for tu in self.token_usage)

    @property
    def total_tokens(self) -> int:
        """Sum of total_tokens from all token usage entries."""
        return sum(tu.total_tokens for tu in self.token_usage)
