import logging
from typing import Any, Dict, List

logger = logging.getLogger(__name__)


def _get_service(config: Dict[str, Any]):
    from semantic_models.services.factory import get_semantic_models_service
    from semantic_models.services.local_semantic_model_client import LocalSemanticModelClient

    project_key = config.get("project_key")
    client = LocalSemanticModelClient(project_key)
    return get_semantic_models_service(client=client)


def do(payload: Dict, config: Dict, plugin_config: Dict, inputs: Any) -> Dict:
    param_name = payload.get("parameterName")

    logger.info("params_helper.do called: param=%s, config=%s", param_name, config)

    if param_name == "semantic_model_id":
        return list_semantic_models(config)
    elif param_name == "version_number":
        return list_versions(config)

    return {"choices": []}


def list_semantic_models(config: Dict[str, Any]) -> Dict[str, List[Dict[str, str]]]:
    service = _get_service(config)
    if not service:
        return {"choices": []}

    try:
        models = service.list_models()
        print(models)
        choices = []
        for model in models:
            choices.append(
                {
                    "value": model.id,
                    "label": model.name,
                }
            )

        logger.info("list_semantic_models: found %d models", len(choices))
        return {"choices": choices}

    except Exception as e:
        logger.warning("list_semantic_models failed: %s", e)
        return {"choices": []}


def list_versions(config: Dict[str, Any]) -> Dict[str, List[Dict[str, str]]]:
    model_id = config.get("semantic_model_id")
    service = _get_service(config)

    if not model_id or not service:
        return {"choices": [{"value": "", "label": "Active version (default)"}]}

    try:
        model_with_versions = service.get_model(model_id)
        model = model_with_versions.model
        versions = model_with_versions.versions

        choices = [{"value": "", "label": "Active version (default)"}]

        for version in versions:
            version_id = version.id
            version_desc = version.description
            is_active = model.activeVersionId == version_id

            label = version_id
            if version_desc:
                label += f" - {version_desc}"
            if is_active:
                label += " (active)"

            choices.append({"value": version_id, "label": label})

        logger.info("list_versions: found %d versions for model %s", len(choices) - 1, model_id)
        return {"choices": choices}

    except Exception as e:
        logger.warning("list_versions failed: %s", e)
        return {"choices": [{"value": "", "label": "Active version (default)"}]}
