# geney/visualization — Dashboard card data for frontend rendering.
#
# Each function produces a JSON-serializable dict that a frontend
# (D3, Plotly, Canvas) can render directly. No server-side image generation.
#
# Usage:
#     from geney.visualization import card_data
#     data = card_data(result)  # dict with all mechanism cards
#
#     # Or individually:
#     from geney.visualization import splicing_card, tis_card, folding_card
#     splicing = splicing_card(result.splicing, result.transcript)

from ._splicing import splicing_card
from ._tis import tis_card
from ._folding import folding_card
from ._transcription import transcription_card

from ..results import MutationResult

__all__ = [
    "card_data",
    "splicing_card",
    "tis_card",
    "folding_card",
    "transcription_card",
]

# Default: only build full card detail when score > this threshold.
_DEFAULT_DETAIL_THRESHOLD = 0.1


def card_data(result: MutationResult, detail_threshold: float = _DEFAULT_DETAIL_THRESHOLD) -> dict:
    """Build all dashboard card data from a MutationResult.

    Args:
        result: MutationResult from pipeline.
        detail_threshold: Mechanisms scoring at or below this get a slim
            card (score + status only). Those above get the full payload
            with sequences, alignments, and per-site data. Default 0.1.

    Returns:
        JSON-serializable dict ready for frontend consumption.
    """
    scores = result.scores

    # Extract identifiers from whichever sub-result has them
    mut_id = ""
    gene = ""
    for sub in (result.splicing, result.tis, result.folding, result.transcription):
        if sub is not None:
            mut_id = mut_id or getattr(sub, "mut_id", "")
            gene = gene or getattr(sub, "gene", "")

    # Build cards — full detail only when score > threshold
    cards = {}
    card_builders = {
        "splicing": lambda: splicing_card(result.splicing, result.transcript),
        "tis": lambda: tis_card(result.tis),
        "folding": lambda: folding_card(result.folding),
        "transcription": lambda: transcription_card(result.transcription),
    }

    for name, builder in card_builders.items():
        ms = scores[name]
        if ms.score > detail_threshold:
            cards[name] = builder()
        else:
            cards[name] = {
                "type": name,
                "score": ms.score,
                "status": ms.status,
                "reason": ms.reason,
            }

    return {
        "mut_id": mut_id,
        "gene": gene,
        "overall_score": result.overall_score,
        "scores": {name: ms.score for name, ms in scores.items()},
        "statuses": {name: ms.status for name, ms in scores.items()},
        "cards": cards,
    }
