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

from adafri.v1.base.firebase_collection import FirebaseCollectionBase

CREATIVE_COLLECTION = 'workflow_creatives'

CREATIVE_PICKABLE_FIELDS = [
    'id', 'workspaceId', 'scenarioId', 'accountId', 'campaignId',
    'type', 'name', 'headline', 'description', 'ctaText',
    'assetUrl', 'previewUrl', 'status', 'feedback',
    'createdAt', 'updatedAt', 'createdBy',
]

CREATIVE_MUTABLE_FIELDS = [
    'name', 'headline', 'description', 'ctaText',
    'assetUrl', 'previewUrl', 'status', 'feedback', 'scenarioId',
]

CREATIVE_TYPES = ['image', 'video', 'copy', 'html']
CREATIVE_STATUS = ['draft', 'in_review', 'approved', 'rejected']


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


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


class WorkflowCreativeFields:
    @staticmethod
    def check_create_fields(data: dict) -> dict:
        if not data:
            return {'error': 'Missing data'}
        if not data.get('name', '').strip():
            return {'error': 'name is required'}
        if not data.get('workspaceId', '').strip():
            return {'error': 'workspaceId is required'}
        if data.get('type') not in CREATIVE_TYPES:
            return {'error': f"type must be one of: {', '.join(CREATIVE_TYPES)}"}
        return data

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


@dataclass(init=False)
class WorkflowCreative(FirebaseCollectionBase):
    id: str
    workspaceId: str
    scenarioId: Optional[str]
    accountId: str
    campaignId: str
    type: str
    name: str
    headline: str
    description: str
    ctaText: str
    assetUrl: str
    previewUrl: str
    status: str
    feedback: Optional[str]
    createdAt: str
    updatedAt: str
    createdBy: str

    def __init__(self, data=None, **kwargs):
        super().__init__(collection_name=CREATIVE_COLLECTION, **kwargs)
        d = data or {}
        self.id = d.get('id') or _new_id()
        self.workspaceId = d.get('workspaceId', '')
        self.scenarioId = d.get('scenarioId')
        self.accountId = d.get('accountId', '')
        self.campaignId = d.get('campaignId', '')
        self.type = d.get('type', 'image')
        self.name = d.get('name', '')
        self.headline = d.get('headline', '')
        self.description = d.get('description', '')
        self.ctaText = d.get('ctaText', '')
        self.assetUrl = d.get('assetUrl', '')
        self.previewUrl = d.get('previewUrl', '')
        self.status = d.get('status', 'draft')
        self.feedback = d.get('feedback')
        self.createdAt = d.get('createdAt') or _now()
        self.updatedAt = d.get('updatedAt') or _now()
        self.createdBy = d.get('createdBy', '')

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

    def to_dict(self) -> dict:
        return {
            'id': self.id,
            'workspaceId': self.workspaceId,
            'scenarioId': self.scenarioId,
            'accountId': self.accountId,
            'campaignId': self.campaignId,
            'type': self.type,
            'name': self.name,
            'headline': self.headline,
            'description': self.description,
            'ctaText': self.ctaText,
            'assetUrl': self.assetUrl,
            'previewUrl': self.previewUrl,
            'status': self.status,
            'feedback': self.feedback,
            'createdAt': self.createdAt,
            'updatedAt': self.updatedAt,
            'createdBy': self.createdBy,
        }

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

    @classmethod
    def find(cls, creative_id: str, account_id: str = None) -> 'Optional[WorkflowCreative]':
        inst = cls()
        doc = inst.collection().document(creative_id).get()
        if not doc.exists:
            return None
        data = {**doc.to_dict(), 'id': doc.id}
        if account_id and data.get('accountId') != account_id:
            return None
        return cls(data)

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

    @classmethod
    def listByScenario(cls, scenario_id: str) -> 'list[WorkflowCreative]':
        inst = cls()
        docs = inst.collection().where('scenarioId', '==', scenario_id).stream()
        return [cls({**d.to_dict(), 'id': d.id}) for d in docs]

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

    def update(self, data: dict) -> 'WorkflowCreative':
        filtered = {k: v for k, v in data.items() if k in CREATIVE_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()
