from __future__ import annotations

from typing import Any

from ..spec_models import PortalSourceType, SolutionSpec
from .form_compiler import default_member_auth
from .icon_utils import encode_workspace_icon


def compile_portal(spec: SolutionSpec) -> dict[str, Any] | None:
    if not spec.preferences.create_portal or not spec.portal.enabled or not spec.portal.sections:
        return None
    components: list[dict[str, Any]] = []
    for ordinal, section in enumerate(spec.portal.sections, start=1):
        component: dict[str, Any] = {
            "sectionId": section.section_id,
            "title": section.title,
            "sourceType": section.source_type.value,
            "ordinal": ordinal,
            **section.config,
        }
        if section.source_type == PortalSourceType.chart:
            component["chartRef"] = {"entity_id": section.entity_id, "chart_id": section.chart_id}
        elif section.source_type == PortalSourceType.view:
            component["viewRef"] = {"entity_id": section.entity_id, "view_id": section.view_id}
        elif section.source_type == PortalSourceType.text:
            component["text"] = section.text or ""
        elif section.source_type == PortalSourceType.link:
            component["url"] = section.url or ""
        components.append(component)
    return {
        "create_payload": {
            "dashName": spec.portal.name or f"{spec.solution_name} 首页",
            "dashIcon": encode_workspace_icon(
                icon=spec.portal.icon,
                color=spec.portal.color,
                title=spec.portal.name or f"{spec.solution_name} 首页",
                fallback_icon_name="view-grid",
            ),
            "auth": default_member_auth(),
            "hideCopyright": False,
            "tags": [{"tagId": "__PACKAGE_TAG_ID__", "ordinal": 1}],
            "dashGlobalConfig": {"layout": "default"},
        },
        "update_payload": {
            "dashName": spec.portal.name or f"{spec.solution_name} 首页",
            "dashIcon": encode_workspace_icon(
                icon=spec.portal.icon,
                color=spec.portal.color,
                title=spec.portal.name or f"{spec.solution_name} 首页",
                fallback_icon_name="view-grid",
            ),
            "auth": default_member_auth(),
            "hideCopyright": False,
            "tags": [{"tagId": "__PACKAGE_TAG_ID__", "ordinal": 1}],
            "dashGlobalConfig": {"layout": "default"},
            "components": components,
            **spec.portal.config,
        },
    }
