from __future__ import annotations

from typing import Any


PROJECT_TYPE_ADVANCED_EXTRACTED_CONTENT = "advanced_extracted_content"
PROJECT_TYPE_OFFICIAL_EXTERNAL_LIVERY = "official_external_livery"

DEFAULT_PROJECT_TYPE = PROJECT_TYPE_ADVANCED_EXTRACTED_CONTENT

KNOWN_PROJECT_TYPES = {
    PROJECT_TYPE_ADVANCED_EXTRACTED_CONTENT,
    PROJECT_TYPE_OFFICIAL_EXTERNAL_LIVERY,
}

PROJECT_TYPE_ALIASES = {
    "advanced": PROJECT_TYPE_ADVANCED_EXTRACTED_CONTENT,
    "advanced_extracted": PROJECT_TYPE_ADVANCED_EXTRACTED_CONTENT,
    "advanced_extracted_content": PROJECT_TYPE_ADVANCED_EXTRACTED_CONTENT,
    "advanced_liverylab_project": PROJECT_TYPE_ADVANCED_EXTRACTED_CONTENT,
    "created": PROJECT_TYPE_ADVANCED_EXTRACTED_CONTENT,
    "legacy": PROJECT_TYPE_ADVANCED_EXTRACTED_CONTENT,
    "liverylab": PROJECT_TYPE_ADVANCED_EXTRACTED_CONTENT,
    "official": PROJECT_TYPE_OFFICIAL_EXTERNAL_LIVERY,
    "official_external": PROJECT_TYPE_OFFICIAL_EXTERNAL_LIVERY,
    "official_external_library": PROJECT_TYPE_OFFICIAL_EXTERNAL_LIVERY,
    "official_external_livery": PROJECT_TYPE_OFFICIAL_EXTERNAL_LIVERY,
    "official_external_project": PROJECT_TYPE_OFFICIAL_EXTERNAL_LIVERY,
    "external_livery": PROJECT_TYPE_OFFICIAL_EXTERNAL_LIVERY,
}


def normalize_project_type(value: Any, default: str = DEFAULT_PROJECT_TYPE) -> str:
    raw = str(value or "").strip().lower().replace("-", "_").replace(" ", "_")
    if raw in KNOWN_PROJECT_TYPES:
        return raw
    if raw in PROJECT_TYPE_ALIASES:
        return PROJECT_TYPE_ALIASES[raw]
    return default


def project_type_for_entry(entry: dict[str, Any] | None) -> str:
    data = entry if isinstance(entry, dict) else {}
    return normalize_project_type(
        data.get("project_type")
        or data.get("projectType")
        or data.get("workflow_type")
        or data.get("workflowType")
    )


def with_project_type(entry: dict[str, Any], project_type: Any = None) -> dict[str, Any]:
    next_entry = dict(entry)
    next_entry["project_type"] = normalize_project_type(project_type or project_type_for_entry(entry))
    return next_entry
