"""Data models for migration tracking and reporting."""

from dataclasses import dataclass, field
from typing import List, Optional
from datetime import datetime


@dataclass
class CollectionMigration:
    """Tracks the migration of a single collection."""
    
    old_collection_id: str
    old_collection_name: str
    old_model: str
    new_model: str
    new_collection_id: Optional[str] = None
    new_collection_name: Optional[str] = None
    job_id: Optional[str] = None
    status: str = "pending"  # pending, success, failed, skipped
    error: Optional[str] = None
    rag_failed: bool = False
    
    def mark_success(self, new_collection_id: str, new_collection_name: str, job_id: str):
        """Mark migration as successful."""
        self.status = "success"
        self.new_collection_id = new_collection_id
        self.new_collection_name = new_collection_name
        self.job_id = job_id
    
    def mark_failed(self, error: str):
        """Mark migration as failed."""
        self.status = "failed"
        self.error = error
    
    def mark_skipped(self, reason: str):
        """Mark migration as skipped."""
        self.status = "skipped"
        self.error = reason


@dataclass
class UserMigration:
    """Tracks all migrations for a single user."""
    
    username: str
    user_id: str
    collections: List[CollectionMigration] = field(default_factory=list)
    
    @property
    def total_collections(self) -> int:
        return len(self.collections)
    
    @property
    def successful_migrations(self) -> int:
        return sum(1 for c in self.collections if c.status == "success")
    
    @property
    def failed_migrations(self) -> int:
        return sum(1 for c in self.collections if c.status == "failed")
    
    @property
    def skipped_migrations(self) -> int:
        return sum(1 for c in self.collections if c.status == "skipped")

    @property
    def rag_failures(self) -> int:
        return sum(1 for c in self.collections if c.rag_failed)


@dataclass
class MigrationReport:
    """Complete migration report with summary."""
    
    start_time: str
    end_time: Optional[str] = None
    config: Optional[dict] = None
    users: List[UserMigration] = field(default_factory=list)
    
    @property
    def summary(self) -> dict:
        """Generate summary statistics."""
        total_collections = sum(u.total_collections for u in self.users)
        successful = sum(u.successful_migrations for u in self.users)
        failed = sum(u.failed_migrations for u in self.users)
        skipped = sum(u.skipped_migrations for u in self.users)
        rag_failures = sum(u.rag_failures for u in self.users)

        return {
            "total_users": len(self.users),
            "total_collections": total_collections,
            "successful_migrations": successful,
            "failed_migrations": failed,
            "skipped_migrations": skipped,
            "rag_failures": rag_failures,
            "duration": self._calculate_duration(),
        }
    
    def _calculate_duration(self) -> Optional[str]:
        """Calculate total duration."""
        if not self.end_time:
            return None
        try:
            start = datetime.fromisoformat(self.start_time)
            end = datetime.fromisoformat(self.end_time)
            duration = end - start
            return str(duration)
        except Exception:
            return None
    
    def complete(self):
        """Mark report as complete with end time."""
        self.end_time = datetime.now().isoformat()
