# File: src/noveler/infrastructure/services/legacy_format_converter.py
# Purpose: Convert detailed 10-stage outputs to legacy 5-stage format for backward compatibility.
# Context: Extracted from unified_session_executor to isolate legacy conversion logic.
"""Legacy format converter for detailed execution stages."""

from __future__ import annotations

from collections.abc import Mapping

from noveler.application.services.a30_compatibility_adapter import (
    A30CompatibilityAdapter,
    CompatibilityMode,
)
from noveler.domain.value_objects.detailed_execution_stage import DetailedExecutionStage
from noveler.domain.value_objects.five_stage_writing_execution import ExecutionStage


class LegacyFormatConverter:
    """Converts detailed-stage outputs into their legacy five-stage equivalents."""

    def __init__(self, compatibility_adapter: A30CompatibilityAdapter | None = None) -> None:
        """Initialize the converter with an optional adapter.

        Args:
            compatibility_adapter: Adapter to use for stage conversion. If not provided,
                a default adapter will be created.
        """
        self.compatibility_adapter = compatibility_adapter or A30CompatibilityAdapter(
            CompatibilityMode.A30_DETAILED_TEN_STAGE
        )

    def convert_to_legacy_format(
        self, detailed_outputs: Mapping[DetailedExecutionStage, str]
    ) -> Mapping[ExecutionStage, str]:
        """Combine detailed-stage outputs into their legacy equivalents.

        Args:
            detailed_outputs: Mapping of detailed execution stages to their outputs.

        Returns:
            Mapping of legacy execution stages to combined outputs.
        """
        if not detailed_outputs:
            return {}

        legacy_map: dict[ExecutionStage, list[str]] = {}
        for stage, output in detailed_outputs.items():
            legacy_stage = self.compatibility_adapter.convert_detailed_to_legacy(stage)
            legacy_map.setdefault(legacy_stage, []).append(output)

        return {stage: "\n".join(part for part in parts if part).strip() for stage, parts in legacy_map.items()}
