from __future__ import annotations

from typing import Any

from liverylab_core import project_types


SCOPE_ADVANCED = "advanced"
SCOPE_OFFICIAL = "official"
SCOPE_ALL = "all"

KNOWN_SCOPES = {
    SCOPE_ADVANCED,
    SCOPE_OFFICIAL,
    SCOPE_ALL,
}


def normalize_scope(value: Any, default: str = SCOPE_ALL) -> str:
    raw = str(value or "").strip().lower().replace("-", "_").replace(" ", "_")
    aliases = {
        "advanced_extracted": SCOPE_ADVANCED,
        "advanced_extracted_content": SCOPE_ADVANCED,
        "advanced_liverylab_project": SCOPE_ADVANCED,
        "legacy": SCOPE_ADVANCED,
        "liverylab": SCOPE_ADVANCED,
        "official_external": SCOPE_OFFICIAL,
        "official_external_livery": SCOPE_OFFICIAL,
        "external_livery": SCOPE_OFFICIAL,
    }
    if raw in KNOWN_SCOPES:
        return raw
    if raw in aliases:
        return aliases[raw]
    return default if default in KNOWN_SCOPES else SCOPE_ALL


def scope_for_entry(entry: dict[str, Any] | None) -> str:
    data = entry if isinstance(entry, dict) else {}
    project_type = project_types.project_type_for_entry(data)
    if project_type == project_types.PROJECT_TYPE_OFFICIAL_EXTERNAL_LIVERY:
        return SCOPE_OFFICIAL
    return SCOPE_ADVANCED


def entry_matches_scope(entry: dict[str, Any] | None, scope: Any) -> bool:
    clean_scope = normalize_scope(scope)
    if clean_scope == SCOPE_ALL:
        return True
    return scope_for_entry(entry) == clean_scope
