#!/usr/bin/env python3
"""
전문가 토론 코디네이터 (메인 관리자 전용)

메인 관리자가 sessions_spawn 툴을 사용하여 각 전문가를 실제 별도 세션으로 호출
"""

import json
from datetime import datetime
from pathlib import Path
from typing import Dict, List


class ExpertDebateCoordinator:
    """전문가 토론 코디네이터 (메인 관리자 호출 방식)"""

    def __init__(self):
        self.workspace_path = Path("/home/jay/workspace")
        self.debate_results_dir = self.workspace_path / "memory" / "debates"
        self.debate_results_dir.mkdir(exist_ok=True)

        # 전문가 페르소나 정의
        self.expert_personas = {
            "frontend": {
                "name": "프론트엔드 아키텍트",
                "expertise": "React, Vue, Next.js, 성능 최적화, 사용자 경험",
                "focus": "UI/UX, 성능, 접근성, 반응형 디자인",
            },
            "backend": {
                "name": "백엔드 아키텍트",
                "expertise": "FastAPI, Django, Node.js, 데이터베이스, API 설계",
                "focus": "확장성, 보안, 성능, 데이터 무결성",
            },
            "uiux": {
                "name": "UI/UX 디자이너",
                "expertise": "사용자 경험, 인터랙션 디자인, 접근성, 브랜딩",
                "focus": "사용자 여정, 직관성, 브랜드 일관성",
            },
            "legal": {
                "name": "법률 자문",
                "expertise": "개인정보보호법, 전자상거래법, 저작권법, 이용약관",
                "focus": "법적 리스크, 컴플라이언스, 이용약관",
            },
            "devops": {
                "name": "DevOps 엔지니어",
                "expertise": "CI/CD, Docker, AWS/GCP, 모니터링, 보안",
                "focus": "배포 자동화, 인프라 확장성, 모니터링",
            },
            "security": {
                "name": "보안 전문가",
                "expertise": "OWASP, 인증/인가, 암호화, 취약점 분석",
                "focus": "보안 아키텍처, 데이터 보호, 침해 대응",
            },
        }

    def generate_expert_tasks(self, spec: Dict, question: str) -> Dict[str, str]:
        """각 전문가별 task 설명 생성 (메인 관리자가 sessions_spawn으로 호출할 내용)"""

        tasks = {}

        for expert_type, persona in self.expert_personas.items():
            task_description = f"""
당신은 {persona['name']}입니다.

전문 분야: {persona['expertise']}
중점 사항: {persona['focus']}

프로젝트 스펙:
{json.dumps(spec, ensure_ascii=False, indent=2)}

토론 주제: {question}

당신의 전문 분야 관점에서 다음을 제시해주세요:

## 주요 고려사항
- 구체적인 기술적 고려사항 3-5개
- 각 항목별 이유와 근거

## 잠재적 문제점
- 예상되는 문제점 2-3개
- 각 문제점의 심각도와 해결 방안

## 권장 사항
- 구체적인 권장 사항 2-3개
- 우선순위와 이유

## 다른 전문가와 의견 충돌 가능성
- 프론트엔드/백엔드/디자인/법률/DevOps/보안 중 의견이 다를 수 있는 부분
- 구체적인 충돌 포인트와 타협 방안

**중요:** 일반적인 답변이 아닌, 이 프로젝트에 구체적인 답변을 제시해주세요.
"""

            tasks[expert_type] = task_description

        return tasks

    def find_consensus(self, opinions: List[Dict]) -> Dict:
        """합의점 도출 (메인 관리자가 수집한 의견을 전달)"""

        consensus_points = []
        conflicts = []

        # 공통 권장 사항 추출
        all_recommendations = []
        for opinion in opinions:
            if "권장 사항" in opinion.get("opinion", ""):
                all_recommendations.append(opinion["opinion"])

        # 의견 충돌 분석
        for i, opinion1 in enumerate(opinions):
            for j, opinion2 in enumerate(opinions[i + 1 :], i + 1):
                if "의견 충돌" in opinion1.get("opinion", "") or "의견 충돌" in opinion2.get("opinion", ""):
                    conflicts.append(
                        {
                            "expert1": opinion1.get("expert_name", "Unknown"),
                            "expert2": opinion2.get("expert_name", "Unknown"),
                            "potential_conflict": True,
                        }
                    )

        return {"consensus_points": consensus_points, "conflicts": conflicts, "total_experts": len(opinions)}

    def save_debate_result(self, spec: Dict, question: str, opinions: List[Dict]) -> str:
        """토론 결과 저장"""

        debate_id = f"debate-{datetime.now().strftime('%Y%m%d-%H%M%S')}"
        consensus = self.find_consensus(opinions)

        result = {
            "debate_id": debate_id,
            "question": question,
            "spec": spec,
            "opinions": opinions,
            "consensus": consensus,
            "timestamp": datetime.now().isoformat(),
        }

        result_file = self.debate_results_dir / f"{debate_id}.json"
        with open(result_file, "w", encoding="utf-8") as f:
            json.dump(result, f, ensure_ascii=False, indent=2)

        return str(result_file)


def main():
    import sys

    coordinator = ExpertDebateCoordinator()

    if len(sys.argv) > 1 and sys.argv[1] == "demo":
        # 데모: task 설명 생성
        demo_spec = {
            "project": "쇼핑몰 플랫폼",
            "features": ["상품 검색", "장바구니", "결제", "리뷰"],
            "tech_stack": ["React", "FastAPI", "PostgreSQL"],
            "target": "일반 소비자",
        }

        question = "이 쇼핑몰 플랫폼의 최적 아키텍처는 무엇인가요?"

        tasks = coordinator.generate_expert_tasks(demo_spec, question)

        print("📝 전문가별 Task 설명 생성 완료:")
        for expert_type, task in tasks.items():
            print(f"\n{expert_type}:")
            print(task[:100] + "...")

        print("\n✅ 메인 관리자가 각 task를 sessions_spawn으로 호출하면 됩니다.")

    else:
        print("사용법:")
        print("  python3 memory/expert-debate-coordinator.py demo")
        print("\n메인 관리자 사용법:")
        print("  coordinator = ExpertDebateCoordinator()")
        print("  tasks = coordinator.generate_expert_tasks(spec, question)")
        print("  # 각 task를 sessions_spawn으로 호출")
        print("  # 결과를 coordinator.find_consensus()에 전달")


if __name__ == "__main__":
    main()
