"""
Workflow Feedback — Tracks workflow recommendation adoption and effectiveness.

PRD §5.2 — Workflow Recommendation Feedback:
    - Which workflows were recommended
    - Whether the agent adopted them
    - Whether they succeeded

PRD §7.3 — Adoption Detection:
    If agent execution steps contain workflow step keywords → adopted=True

PRD §7.4 — Outcome Tracking
"""

import time
import logging
from typing import List, Dict, Optional
from openmemo.memory_feedback.feedback_store import (
    FeedbackStore, WorkflowFeedbackRecord
)
from openmemo.memory_feedback.quality_scorer import QualityScorer

logger = logging.getLogger("openmemo.feedback")


class WorkflowFeedback:
    """
    Tracks workflow recommendation lifecycle: recommend → adopt → outcome.

    Usage:
        wf = WorkflowFeedback(store)

        # Record recommendation
        wf.on_recommend(workflow_id="wf_001", task_id="task_1")

        # After agent step: detect adoption
        wf.on_step(task_id="task_1", step_text="docker build && docker compose up",
                    workflow_id="wf_001",
                    workflow_steps=["docker build", "docker compose", "health check"])

        # On task complete: record outcome
        wf.on_complete(task_id="task_1", workflow_id="wf_001", success=True)
    """

    def __init__(self, store: FeedbackStore, scorer: QualityScorer = None):
        self.store = store
        self.scorer = scorer or QualityScorer(store)
        # In-memory: task_id:workflow_id → pending state
        self._pending: Dict[str, Dict] = {}

    def on_recommend(self, workflow_id: str, task_id: str = "",
                      agent_id: str = "") -> str:
        """Record that a workflow was recommended."""
        fb = WorkflowFeedbackRecord(
            workflow_id=workflow_id,
            task_id=task_id,
            agent_id=agent_id,
            recommended=True,
            adopted=False,
            success=False,
        )
        self.store.record_workflow_feedback(fb)
        self._pending[f"{task_id}:{workflow_id}"] = {
            "workflow_id": workflow_id,
            "task_id": task_id,
            "agent_id": agent_id,
            "recommended": True,
            "adopted": False,
            "adoption_rate": 0.0,
            "step_matches": 0,
            "total_steps": 0,
        }
        logger.debug("workflow recommend: wf=%s task=%s", workflow_id, task_id)
        return fb.feedback_id

    def on_step(self, task_id: str, step_text: str,
                 workflow_id: str = "", workflow_steps: List[str] = None,
                 agent_id: str = "") -> Dict:
        """
        PRD §7.3 — Detect adoption by comparing agent step to workflow steps.

        Returns detection result: {"adopted": bool, "adoption_rate": float}
        """
        workflow_steps = workflow_steps or []
        if not workflow_steps:
            return {"adopted": False, "adoption_rate": 0.0}

        tl = step_text.lower()
        matches = sum(1 for kw in workflow_steps if kw.lower() in tl)
        adoption_rate = round(matches / len(workflow_steps), 4)
        adopted = adoption_rate >= 0.3

        key = f"{task_id}:{workflow_id}"
        if key in self._pending:
            state = self._pending[key]
            state["step_matches"] += matches
            state["total_steps"] += len(workflow_steps)
            if adopted:
                state["adopted"] = True
                state["adoption_rate"] = adoption_rate

        if adopted and workflow_id:
            fb = WorkflowFeedbackRecord(
                workflow_id=workflow_id,
                task_id=task_id,
                agent_id=agent_id,
                recommended=True,
                adopted=True,
                adoption_rate=adoption_rate,
            )
            self.store.record_workflow_feedback(fb)
            logger.debug("workflow adopted: wf=%s rate=%.2f", workflow_id, adoption_rate)

        return {"adopted": adopted, "adoption_rate": adoption_rate}

    def on_complete(self, task_id: str, workflow_id: str = "",
                     success: bool = False, agent_id: str = "",
                     execution_time: float = 0.0,
                     reuse_detected: bool = False) -> str:
        """
        PRD §7.4 — Record outcome signal on task completion.
        """
        if not workflow_id:
            return ""

        key = f"{task_id}:{workflow_id}"
        state = self._pending.pop(key, {})
        adoption_rate = state.get("adoption_rate", 0.0)
        adopted = state.get("adopted", False)

        fb = WorkflowFeedbackRecord(
            workflow_id=workflow_id,
            task_id=task_id,
            agent_id=agent_id,
            recommended=True,
            adopted=adopted,
            success=success,
            adoption_rate=adoption_rate,
            completion_time=execution_time,
        )
        self.store.record_workflow_feedback(fb)
        logger.debug("workflow outcome: wf=%s success=%s adopted=%s",
                     workflow_id, success, adopted)
        return fb.feedback_id

    def get_quality(self, workflow_id: str) -> dict:
        """Return workflow quality scores from QualityScorer."""
        return self.scorer.score_workflow(workflow_id)

    def get_history(self, workflow_id: str, limit: int = 50) -> list:
        """Return recent feedback records for a workflow."""
        records = self.store.get_workflow_feedback(workflow_id, limit=limit)
        return [r.to_dict() for r in records]
