# Manager Core
# 메인 로직

from typing import Dict, Any, List

from .data import MANAGERS
from .utils import (
    _analyze_context,
    _select_managers_by_context,
    _extract_feature_name,
    _check_pattern,
    _generate_action_items,
    _group_by_phase,
    _generate_recommendations,
)
from .formatter import _format_output


def manager(
    context: str,
    mode: str = "auto",
    managers: List[str] = None,
    include_checklist: bool = True
) -> Dict[str, Any]:
    """
    컨텍스트에 맞는 매니저들의 피드백을 제공합니다.

    Args:
        context: 검토할 내용 (플랜, 코드, 질문 등)
        mode: 'auto' (자동 감지), 'all' (전체), 'specific' (지정)
        managers: mode='specific'일 때 사용할 매니저 목록
        include_checklist: 체크리스트 포함 여부

    Returns:
        각 매니저의 피드백과 추천 사항
    """
    result = {
        "context_analysis": {},
        "active_managers": [],
        "feedback": {},
        "action_items": [],
        "action_items_by_phase": {},
        "combined_checklist": [],
        "warnings": [],
        "recommendations": []
    }

    # 1. 컨텍스트 분석
    detected_contexts = _analyze_context(context)
    result["context_analysis"] = {
        "detected_topics": detected_contexts,
        "context_length": len(context)
    }

    # 2. 활성화할 매니저 결정
    if mode == "all":
        active_managers = list(MANAGERS.keys())
    elif mode == "specific" and managers:
        active_managers = [m.upper() for m in managers if m.upper() in MANAGERS]
    else:  # auto
        active_managers = _select_managers_by_context(context, detected_contexts)

    result["active_managers"] = active_managers

    # 3. 각 매니저의 피드백 생성
    for manager_key in active_managers:
        manager_info = MANAGERS[manager_key]
        feedback = _generate_feedback(manager_key, manager_info, context)
        result["feedback"][manager_key] = feedback

        # 체크리스트 통합
        if include_checklist:
            for item in manager_info.get("checklist", []):
                combined_item = f"[{manager_info['emoji']} {manager_key}] {item}"
                if combined_item not in result["combined_checklist"]:
                    result["combined_checklist"].append(combined_item)

        # 경고 수집
        if feedback.get("warnings"):
            result["warnings"].extend(feedback["warnings"])

    # 3.5. 액션 아이템 생성
    action_items = _generate_action_items(context, active_managers)
    result["action_items"] = action_items
    result["action_items_by_phase"] = _group_by_phase(action_items)

    # 4. 종합 추천 사항
    result["recommendations"] = _generate_recommendations(result)

    # 5. 출력 포맷팅
    result["formatted_output"] = _format_output(result)

    return result


def _generate_feedback(manager_key: str, manager_info: Dict, context: str) -> Dict[str, Any]:
    """매니저별 피드백을 생성합니다."""
    feedback = {
        "emoji": manager_info["emoji"],
        "title": manager_info["title"],
        "focus": manager_info["focus"],
        "questions": [],
        "opinions": [],
        "concerns": [],
        "warnings": [],
        "action_items": [],
        "approval_status": "REVIEW_NEEDED"
    }

    context_lower = context.lower()
    feature_name = _extract_feature_name(context)

    # 1. 컨텍스트 기반 의견 생성
    opinions_dict = manager_info.get("opinions", {})
    detected_topics = _analyze_context(context)

    opinion_added = False
    for topic in detected_topics:
        if topic in opinions_dict:
            opinion = opinions_dict[topic].replace("{feature}", feature_name)
            feedback["opinions"].append(opinion)
            opinion_added = True
            break

    if not opinion_added and "default" in opinions_dict:
        feedback["opinions"].append(opinions_dict["default"])

    # 2. 관련 질문 추가
    for question in manager_info["questions"]:
        question_keywords = question.lower().split()
        if any(kw in context_lower for kw in question_keywords[:3]):
            feedback["questions"].append(question)
            if len(feedback["questions"]) >= 1:
                break

    if not feedback["questions"]:
        feedback["questions"] = manager_info["questions"][:1]

    # 개별 매니저 액션 아이템 생성
    templates = manager_info.get("action_templates", [])
    for template in templates:
        trigger = template.get("trigger", "")
        trigger_patterns = trigger.split("|")
        if any(pattern.lower() in context_lower for pattern in trigger_patterns):
            for action in template.get("actions", []):
                feedback["action_items"].append({
                    "id": action["id"],
                    "action": action["action"],
                    "depends": action.get("depends", []),
                    "verify": action.get("verify", ""),
                    "phase": action.get("phase", "검증")
                })

    # 경고 패턴 체크
    if manager_key == "CSO":
        critical_patterns = manager_info.get("critical_patterns", [])
        for pattern in critical_patterns:
            if pattern.lower() in context_lower or _check_pattern(pattern, context):
                feedback["warnings"].append(f"⚠️ 보안 위험: {pattern}")
                feedback["approval_status"] = "BLOCKED"

    if manager_key == "CDO":
        anti_patterns = manager_info.get("anti_patterns", [])
        for pattern in anti_patterns:
            if pattern.lower() in context_lower:
                feedback["concerns"].append(f"🎨 디자인 우려: {pattern}")

    if manager_key == "ERROR":
        if "error" in context_lower or "exception" in context_lower:
            feedback["concerns"].append("🔥 에러 처리 로직 검토 필요")
            feedback["questions"].append("5 Whys 분석이 완료되었나요?")

    return feedback


def ask_manager(manager_key: str, question: str) -> Dict[str, Any]:
    """특정 매니저에게 질문합니다."""
    manager_key = manager_key.upper()
    if manager_key not in MANAGERS:
        return {"error": f"Unknown manager: {manager_key}"}

    return manager(
        context=question,
        mode="specific",
        managers=[manager_key]
    )
