from __future__ import annotations

from dataclasses import asdict
from typing import Any

from app.domain.editor import VariantChange
from app.domain.editor_builder import build_runtime_payload_from_changes
from app.domain.mappers import to_release
from app.repositories.directus.releases import ReleaseRepository
from app.repositories.directus.variant_changes import VariantChangeRepository
from app.repositories.directus.variants import VariantRepository
from app.schemas.admin import BuildReleaseRequest, ReleaseLifecycleResponse, ReleaseRead, release_to_read_model


class ReleaseService:
    """Application service for release and snapshot lifecycle."""

    def __init__(
        self,
        repository: ReleaseRepository | None = None,
        variant_repository: VariantRepository | None = None,
        change_repository: VariantChangeRepository | None = None,
    ) -> None:
        self.repository = repository or ReleaseRepository()
        self.variant_repository = variant_repository or VariantRepository()
        self.change_repository = change_repository or VariantChangeRepository()

    async def list_releases(
        self,
        experiment_id: str | None = None,
        access_token: str | None = None,
    ) -> list[ReleaseRead]:
        params: dict[str, Any] | None = None
        if experiment_id:
            params = {"filter[experiment_id][_eq]": experiment_id}

        items = await self.repository.list(params=params, access_token=access_token)
        return [release_to_read_model(to_release(item)) for item in items]

    async def get_release(
        self,
        release_id: str,
        access_token: str | None = None,
    ) -> ReleaseRead | None:
        item = await self.repository.get(release_id, access_token=access_token)
        if not item:
            return None
        return release_to_read_model(to_release(item))

    async def build_release(
        self,
        payload: BuildReleaseRequest,
        access_token: str | None = None,
    ) -> ReleaseRead:
        experiment_id = payload.experiment_id

        # Fetch all variants for the experiment
        variant_items = await self.variant_repository.list(
            params={"filter[experiment_id][_eq]": experiment_id},
            access_token=access_token,
        )

        # Build per-variant runtime payloads
        variants_payload: list[dict[str, Any]] = []
        for variant_item in variant_items:
            variant_id = str(variant_item["id"])
            change_items = await self.change_repository.list(
                params={"filter[variant_id][_eq]": variant_id},
                access_token=access_token,
            )
            changes = [
                VariantChange(
                    id=str(c["id"]),
                    variant_id=variant_id,
                    change_type=str(c.get("change_type", "")),
                    selector_type=str(c.get("selector_type", "")),
                    selector_value=str(c.get("selector_value", "")),
                    sort_order=int(c.get("sort_order", 0)),
                    payload=c.get("payload"),
                )
                for c in change_items
            ]
            runtime_payload = build_runtime_payload_from_changes(variant_id, changes)
            variants_payload.append({
                "variant_id": variant_id,
                "variant_key": str(variant_item.get("variant_key", "")),
                "traffic_weight": int(variant_item.get("traffic_weight", 0)),
                "operations": [asdict(op) for op in runtime_payload.operations],
            })

        # Determine next version_no
        existing = await self.repository.list(
            params={"filter[experiment_id][_eq]": experiment_id, "sort": "-version_no", "limit": "1"},
            access_token=access_token,
        )
        next_version = (int(existing[0]["version_no"]) + 1) if existing else 1

        new_release = await self.repository.create(
            {
                "experiment_id": experiment_id,
                "version_no": next_version,
                "status": "draft",
                "runtime_payload": {"variants": variants_payload},
            },
            access_token=access_token,
        )
        return release_to_read_model(to_release(new_release))

    async def publish_release(
        self,
        release_id: str,
        access_token: str | None = None,
    ) -> ReleaseLifecycleResponse | None:
        # Fetch the target release to get experiment_id
        target = await self.repository.get(release_id, access_token=access_token)
        if not target:
            return None

        experiment_id = str(target["experiment_id"])

        # Demote any currently published release in this experiment to draft
        currently_published = await self.repository.list(
            params={
                "filter[experiment_id][_eq]": experiment_id,
                "filter[status][_eq]": "published",
            },
            access_token=access_token,
        )
        for other in currently_published:
            if str(other["id"]) != release_id:
                await self.repository.update(str(other["id"]), {"status": "draft"}, access_token=access_token)

        item = await self.repository.update(release_id, {"status": "published"}, access_token=access_token)
        if not item:
            return None
        return ReleaseLifecycleResponse(
            id=str(item["id"]),
            status=str(item["status"]),
            version_no=int(item["version_no"]),
        )

    async def rollback_release(
        self,
        release_id: str,
        access_token: str | None = None,
    ) -> ReleaseLifecycleResponse | None:
        # Fetch the target release to get experiment_id and version_no
        target = await self.repository.get(release_id, access_token=access_token)
        if not target:
            return None

        experiment_id = str(target["experiment_id"])
        current_version_no = int(target["version_no"])

        # Demote the current release back to draft
        await self.repository.update(release_id, {"status": "draft"}, access_token=access_token)

        # Find the most recent draft release with an earlier version_no to restore
        previous_candidates = await self.repository.list(
            params={
                "filter[experiment_id][_eq]": experiment_id,
                "filter[status][_eq]": "draft",
                "filter[version_no][_lt]": str(current_version_no),
                "sort": "-version_no",
                "limit": "1",
            },
            access_token=access_token,
        )

        if previous_candidates:
            restored = await self.repository.update(
                str(previous_candidates[0]["id"]),
                {"status": "published"},
                access_token=access_token,
            )
            if restored:
                return ReleaseLifecycleResponse(
                    id=str(restored["id"]),
                    status=str(restored["status"]),
                    version_no=int(restored["version_no"]),
                )

        # No previous release to restore — return the now-drafted current release
        updated = await self.repository.get(release_id, access_token=access_token)
        if not updated:
            return None
        return ReleaseLifecycleResponse(
            id=str(updated["id"]),
            status=str(updated["status"]),
            version_no=int(updated["version_no"]),
        )

    async def archive_release(
        self,
        release_id: str,
        access_token: str | None = None,
    ) -> ReleaseLifecycleResponse | None:
        item = await self.repository.update(release_id, {"status": "archived"}, access_token=access_token)
        if not item:
            return None
        return ReleaseLifecycleResponse(
            id=str(item["id"]),
            status=str(item["status"]),
            version_no=int(item["version_no"]),
        )
