"""
Import session management for resumable workflows.
"""

import json
from dataclasses import asdict, dataclass
from datetime import datetime
from pathlib import Path
from typing import (
    Any,
    Dict,
    List,
    Optional,
)


@dataclass
class ImportDecision:
    """Represents a conflict resolution decision."""

    conflict_id: str
    existing_record: Dict[str, Any]
    new_record: Dict[str, Any]
    decision: str  # 'replace', 'keep_both', 'skip', 'keep_existing'
    timestamp: str


@dataclass
class ImportSession:
    """Manages import session state for resumability."""

    session_id: str
    source_file: str
    target_dataset: str  # 'reference' or 'usage-reference'
    start_time: str
    total_conflicts: int
    resolved_conflicts: int
    decisions: List[ImportDecision]
    last_saved: str
    completed: bool = False

    @classmethod
    def create_new(
        cls,
        session_id: str,
        source_file: str,
        target_dataset: str,
        total_conflicts: int,
    ):
        """Create a new import session."""
        now = datetime.now().isoformat()
        return cls(
            session_id=session_id,
            source_file=source_file,
            target_dataset=target_dataset,
            start_time=now,
            total_conflicts=total_conflicts,
            resolved_conflicts=0,
            decisions=[],
            last_saved=now,
        )

    def add_decision(
        self, conflict_id: str, existing_record: dict, new_record: dict, decision: str
    ):
        """Add a conflict resolution decision."""
        import_decision = ImportDecision(
            conflict_id=conflict_id,
            existing_record=existing_record,
            new_record=new_record,
            decision=decision,
            timestamp=datetime.now().isoformat(),
        )
        self.decisions.append(import_decision)
        self.resolved_conflicts += 1
        self.last_saved = datetime.now().isoformat()

    def get_progress_info(self) -> Dict[str, Any]:
        """Get human-readable progress information."""
        return {
            "session_id": self.session_id,
            "source_file": Path(self.source_file).name,
            "target_dataset": self.target_dataset,
            "progress": f"{self.resolved_conflicts}/{self.total_conflicts}",
            "percentage": round(
                (self.resolved_conflicts / self.total_conflicts) * 100, 1
            )
            if self.total_conflicts > 0
            else 0,
            "remaining": self.total_conflicts - self.resolved_conflicts,
            "completed": self.completed,
        }

    def mark_completed(self):
        """Mark session as completed."""
        self.completed = True
        self.last_saved = datetime.now().isoformat()


class ImportSessionManager:
    """Manages import sessions for resumable workflows."""

    def __init__(self, sessions_dir: Path = Path(".import_sessions")):
        self.sessions_dir = sessions_dir
        self.sessions_dir.mkdir(exist_ok=True)

    def _get_session_file(self, session_id: str) -> Path:
        """Get path to session file."""
        return self.sessions_dir / f"{session_id}.json"

    def create_session(
        self,
        session_id: str,
        source_file: str,
        target_dataset: str,
        total_conflicts: int,
    ) -> ImportSession:
        """Create a new import session."""
        session = ImportSession.create_new(
            session_id, source_file, target_dataset, total_conflicts
        )
        self.save_session(session)
        return session

    def load_session(self, session_id: str) -> Optional[ImportSession]:
        """Load an existing session."""
        session_file = self._get_session_file(session_id)
        if not session_file.exists():
            return None

        try:
            with open(session_file) as f:
                data = json.load(f)

            # Convert decisions back to ImportDecision objects
            decisions = [
                ImportDecision(**decision_data)
                for decision_data in data.get("decisions", [])
            ]
            data["decisions"] = decisions

            return ImportSession(**data)
        except Exception:
            return None

    def save_session(self, session: ImportSession):
        """Save session to disk."""
        session_file = self._get_session_file(session.session_id)

        # Convert to dict for JSON serialization
        session_data = asdict(session)

        with open(session_file, "w") as f:
            json.dump(session_data, f, indent=2)

    def list_sessions(self) -> List[Dict[str, Any]]:
        """List all available sessions."""
        sessions = []
        for session_file in self.sessions_dir.glob("*.json"):
            session_id = session_file.stem
            session = self.load_session(session_id)
            if session:
                sessions.append(session.get_progress_info())

        return sessions

    def cleanup_completed_sessions(self, keep_days: int = 7):
        """Clean up old completed sessions."""
        cutoff_time = datetime.now().timestamp() - (keep_days * 24 * 60 * 60)

        for session_file in self.sessions_dir.glob("*.json"):
            if session_file.stat().st_mtime < cutoff_time:
                session = self.load_session(session_file.stem)
                if session and session.completed:
                    session_file.unlink()

    def delete_session(self, session_id: str):
        """Delete a specific session."""
        session_file = self._get_session_file(session_id)
        if session_file.exists():
            session_file.unlink()


def generate_session_id(source_file: str, target_dataset: str) -> str:
    """Generate a unique session ID."""
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    file_name = Path(source_file).stem
    return f"{target_dataset}_{file_name}_{timestamp}"
