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

from adafri.v1.base.firebase_collection import FirebaseCollectionBase

SCENARIO_COLLECTION = 'workflow_scenarios'

SCENARIO_PICKABLE_FIELDS = [
    'id', 'workspaceId', 'accountId', 'campaignId',
    'name', 'description', 'budget', 'bidStrategy',
    'targetAudience', 'expectedReach', 'expectedClicks', 'expectedConversions',
    'status', 'score', 'ownerId', 'allowedTeamIds', 'allowedMemberUids',
    'createdAt', 'updatedAt', 'createdBy',
]

SCENARIO_MUTABLE_FIELDS = [
    'name', 'description', 'budget', 'bidStrategy',
    'targetAudience', 'expectedReach', 'expectedClicks', 'expectedConversions',
    'status', 'score', 'allowedTeamIds', 'allowedMemberUids',
]

SCENARIO_STATUS = ['draft', 'selected', 'rejected']


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


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


class WorkflowScenarioFields:
    @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'}
        return data

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


@dataclass(init=False)
class WorkflowScenario(FirebaseCollectionBase):
    id: str
    workspaceId: str
    accountId: str
    campaignId: str
    name: str
    description: str
    budget: float
    bidStrategy: str
    targetAudience: dict
    expectedReach: int
    expectedClicks: int
    expectedConversions: int
    status: str
    score: float
    ownerId: str
    allowedTeamIds: list
    allowedMemberUids: list
    createdAt: str
    updatedAt: str
    createdBy: str

    def __init__(self, data=None, **kwargs):
        super().__init__(collection_name=SCENARIO_COLLECTION, **kwargs)
        d = data or {}
        self.id = d.get('id') or _new_id()
        self.workspaceId = d.get('workspaceId', '')
        self.accountId = d.get('accountId', '')
        self.campaignId = d.get('campaignId', '')
        self.name = d.get('name', '')
        self.description = d.get('description', '')
        self.budget = float(d.get('budget') or 0)
        self.bidStrategy = d.get('bidStrategy', 'TARGET_CPA')
        self.targetAudience = dict(d.get('targetAudience') or {})
        self.expectedReach = int(d.get('expectedReach') or 0)
        self.expectedClicks = int(d.get('expectedClicks') or 0)
        self.expectedConversions = int(d.get('expectedConversions') or 0)
        self.status = d.get('status', 'draft')
        self.score = float(d.get('score') or 0)
        self.ownerId = d.get('ownerId', '')
        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', '')

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

    def to_dict(self) -> dict:
        return {
            'id': self.id,
            'workspaceId': self.workspaceId,
            'accountId': self.accountId,
            'campaignId': self.campaignId,
            'name': self.name,
            'description': self.description,
            'budget': self.budget,
            'bidStrategy': self.bidStrategy,
            'targetAudience': self.targetAudience,
            'expectedReach': self.expectedReach,
            'expectedClicks': self.expectedClicks,
            'expectedConversions': self.expectedConversions,
            'status': self.status,
            'score': self.score,
            'ownerId': self.ownerId,
            'allowedTeamIds': self.allowedTeamIds,
            'allowedMemberUids': self.allowedMemberUids,
            '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, scenario_id: str, account_id: str = None) -> 'Optional[WorkflowScenario]':
        inst = cls()
        doc = inst.collection().document(scenario_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[WorkflowScenario]':
        inst = cls()
        docs = inst.collection().where('workspaceId', '==', workspace_id).stream()
        return [cls({**d.to_dict(), 'id': d.id}) for d in docs]

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

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