from dataclasses import dataclass, field
from typing import Optional, List
import time
import uuid
import hashlib


@dataclass
class Project:
    """A shared project workspace."""
    project_id: str = field(default_factory=lambda: f"proj_{uuid.uuid4().hex[:12]}")
    name: str = "Untitled Project"
    room_id: str = ""                   # Room this project is attached to
    created_by: str = ""                # user_id of creator
    created_at: str = field(default_factory=lambda: time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()))
    description: str = ""


@dataclass
class ProjectFile:
    """Metadata for a single file in the project."""
    file_id: str = field(default_factory=lambda: f"file_{uuid.uuid4().hex[:12]}")
    project_id: str = ""
    relative_path: str = ""             # e.g. "src/main.py" — always forward slashes
    size_bytes: int = 0
    content_hash: str = ""              # SHA-256 of file content
    last_modified_by: str = ""          # user_id
    last_modified_at: str = field(default_factory=lambda: time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()))
    is_deleted: bool = False            # Soft delete for sync


@dataclass
class FileChange:
    """A single change event in the project history."""
    change_id: str = field(default_factory=lambda: f"chg_{uuid.uuid4().hex[:12]}")
    project_id: str = ""
    file_id: str = ""
    relative_path: str = ""
    action: str = ""                    # "create" | "update" | "delete" | "rename"
    user_id: str = ""
    user_name: str = ""
    content_hash: str = ""              # Hash after this change
    previous_hash: str = ""             # Hash before this change
    size_bytes: int = 0
    timestamp: str = field(default_factory=lambda: time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()))
    detail: str = ""                    # Optional: "renamed from old.py", etc.


def compute_file_hash(file_path: str) -> str:
    """SHA-256 hash of file content. Returns empty string for missing files."""
    try:
        h = hashlib.sha256()
        with open(file_path, "rb") as f:
            for chunk in iter(lambda: f.read(8192), b""):
                h.update(chunk)
        return h.hexdigest()
    except (FileNotFoundError, PermissionError):
        return ""
