# -*- coding: utf-8 -*-
"""
V2-025 PublishStage - PublishAdapter Bridge

역할:
- PublishStage는 직접 발행하지 않는다.
- PublishAdapter를 호출하고 결과를 PipelineContext에 저장한다.
"""

import time

from services.v2.base_stage import BaseStage
from services.v2.pipeline_result import PipelineResult
from services.v2.publish_adapter import PublishAdapter


class PublishStage(BaseStage):
    name = "publish"

    def __init__(self, adapter=None):
        self.adapter = adapter or PublishAdapter()

    def run(self, context) -> PipelineResult:
        started = time.time()

        context.current_stage = self.name
        context.log("[PUBLISH] start")

        result = self.adapter.publish(context)

        published = result.get("published", [])
        data = result.get("data", {})

        context.put("publish_results", published)
        context.put("publish_count", len(published))
        context.put("publish_data", data)
        context.put("publish_skipped", bool(result.get("skipped", False)))
        context.put("publish_dry_run", bool(result.get("dry_run", False)))

        elapsed = time.time() - started

        if result.get("success"):
            if result.get("dry_run"):
                context.log("[PUBLISH] dry_run target selected")
            elif result.get("skipped"):
                context.log(f"[PUBLISH] skipped: {result.get('message', '')}")
            else:
                context.log(f"[PUBLISH] completed count={len(published)}")
        else:
            context.log(f"[PUBLISH] failed: {result.get('message', '')}")

        return PipelineResult(
            success=result.get("success", False),
            stage=self.name,
            message=result.get("message", ""),
            elapsed=elapsed,
        )
