import uuid
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Any, Optional

from adafri.v1.base.firebase_collection import FirebaseCollectionBase

DOCUMENT_COLLECTION = 'workflow_documents'

DOCUMENT_PICKABLE_FIELDS = [
    'id', 'workspaceId', 'title', 'icon', 'content',
    'isPublished', 'allowedTeamIds', 'allowedMemberUids',
    'createdAt', 'updatedAt', 'createdBy', 'lastEditedBy',
]

DOCUMENT_MUTABLE_FIELDS = [
    'title', 'icon', 'content', 'isPublished', 'lastEditedBy',
    'allowedTeamIds', 'allowedMemberUids',
]


def _now() -> str:
    return datetime.now(timezone.utc).isoformat()


def _new_id() -> str:
    return str(uuid.uuid4())


class WorkflowDocumentFields:
    @staticmethod
    def check_create_fields(data: dict) -> dict:
        if not data:
            return {'error': 'Missing data'}
        if not data.get('workspaceId', '').strip():
            return {'error': 'workspaceId is required'}
        return data

    @staticmethod
    def mutable_keys() -> list:
        return DOCUMENT_MUTABLE_FIELDS


@dataclass(init=False)
class WorkflowDocument(FirebaseCollectionBase):
    id: str
    workspaceId: str
    title: str
    icon: str
    content: str
    isPublished: bool
    allowedTeamIds: list
    allowedMemberUids: list
    createdAt: str
    updatedAt: str
    createdBy: str
    lastEditedBy: str

    def __init__(self, data=None, **kwargs):
        super().__init__(collection_name=DOCUMENT_COLLECTION, **kwargs)
        d = data or {}
        self.id = d.get('id') or _new_id()
        self.workspaceId = d.get('workspaceId', '')
        self.title = d.get('title', 'Untitled')
        self.icon = d.get('icon', '📄')
        self.content = d.get('content', '')
        self.isPublished = bool(d.get('isPublished', False))
        self.allowedTeamIds = list(d.get('allowedTeamIds') or [])
        self.allowedMemberUids = list(d.get('allowedMemberUids') or [])
        self.createdAt = d.get('createdAt') or _now()
        self.updatedAt = d.get('updatedAt') or _now()
        self.createdBy = d.get('createdBy', '')
        self.lastEditedBy = d.get('lastEditedBy', '')

    @classmethod
    def from_dict(cls, obj: Any, **kwargs) -> 'WorkflowDocument':
        return cls(obj, **kwargs)

    def to_dict(self) -> dict:
        return {
            'id': self.id,
            'workspaceId': self.workspaceId,
            'title': self.title,
            'icon': self.icon,
            'content': self.content,
            'isPublished': self.isPublished,
            'allowedTeamIds': self.allowedTeamIds,
            'allowedMemberUids': self.allowedMemberUids,
            'createdAt': self.createdAt,
            'updatedAt': self.updatedAt,
            'createdBy': self.createdBy,
            'lastEditedBy': self.lastEditedBy,
        }

    @staticmethod
    def toListDict(items: list, fields=None) -> list:
        return [item.to_dict() for item in items]

    @classmethod
    def find(cls, doc_id: str) -> 'Optional[WorkflowDocument]':
        inst = cls()
        doc = inst.collection().document(doc_id).get()
        if not doc.exists:
            return None
        return cls({**doc.to_dict(), 'id': doc.id})

    @classmethod
    def listByWorkspace(cls, workspace_id: str) -> 'list[WorkflowDocument]':
        inst = cls()
        docs = (
            inst.collection()
            .where('workspaceId', '==', workspace_id)
            .order_by('updatedAt', direction='DESCENDING')
            .stream()
        )
        return [cls({**d.to_dict(), 'id': d.id}) for d in docs]

    def save(self) -> 'WorkflowDocument':
        self.collection().document(self.id).set(self.to_dict())
        return self

    def update(self, data: dict) -> 'WorkflowDocument':
        filtered = {k: v for k, v in data.items() if k in DOCUMENT_MUTABLE_FIELDS}
        filtered['updatedAt'] = _now()
        self.collection().document(self.id).update(filtered)
        for k, v in filtered.items():
            setattr(self, k, v)
        return self

    def delete(self) -> None:
        self.collection().document(self.id).delete()
