from __future__ import annotations

import logging
from collections.abc import Mapping
from typing import Any


def _summary_from_result(result: Mapping[str, Any]) -> Mapping[str, Any]:
    summary = result.get("summary")
    if isinstance(summary, Mapping):
        return summary
    run = result.get("run")
    if isinstance(run, Mapping) and isinstance(run.get("summary"), Mapping):
        return run["summary"]
    return {}


def _flatten_summary(summary: Mapping[str, Any], *, prefix: str = "") -> list[str]:
    parts: list[str] = []
    for key in sorted(summary):
        value = summary[key]
        name = f"{prefix}{key}"
        if isinstance(value, Mapping):
            parts.extend(_flatten_summary(value, prefix=f"{name}."))
        elif isinstance(value, list):
            if value:
                parts.append(f"{name}={len(value)}")
        else:
            parts.append(f"{name}={value}")
    return parts


def _value_at(summary: Mapping[str, Any], path: str) -> Any:
    value: Any = summary
    for part in path.split("."):
        if not isinstance(value, Mapping) or part not in value:
            return None
        value = value[part]
    return value


def _is_positive(value: Any) -> bool:
    if isinstance(value, bool):
        return value
    if isinstance(value, (int, float)):
        return value > 0
    if isinstance(value, list):
        return len(value) > 0
    return False


def compact_task_result(result: Mapping[str, Any]) -> str:
    task_key = str(result.get("task_key") or "")
    status = str(result.get("status") or "unknown")
    run = result.get("run")
    duration = run.get("duration_ms") if isinstance(run, Mapping) else None

    parts = [f"status={status}"]
    if task_key:
        parts.append(f"task={task_key}")
    if duration is not None:
        parts.append(f"duration={duration}ms")

    summary = _summary_from_result(result)
    if summary:
        parts.extend(_flatten_summary(summary))
    return " ".join(parts)


def task_result_has_activity(result: Mapping[str, Any], activity_keys: tuple[str, ...]) -> bool:
    status = str(result.get("status") or "")
    if status and status != "success":
        return True

    summary = _summary_from_result(result)
    return any(_is_positive(_value_at(summary, key)) for key in activity_keys)


def log_task_result(
    logger: logging.Logger,
    label: str,
    result: Mapping[str, Any],
    *,
    activity_keys: tuple[str, ...] = (),
) -> None:
    line = f"{label}: {compact_task_result(result)}"
    if task_result_has_activity(result, activity_keys):
        logger.info(line)
    else:
        logger.debug(line)
