#!/usr/bin/env python3
"""TheLatent MCP Server - Claude Desktop/Code 연동"""

import os
import json
import sys
from typing import Any

from .bot import Bot

# MCP Protocol 구현
class MCPServer:
    def __init__(self):
        api_key = os.environ.get('THELATENT_API_KEY')
        if not api_key:
            raise ValueError('THELATENT_API_KEY 환경변수가 필요합니다')
        self.bot = Bot(api_key=api_key)
        
    def handle_request(self, request: dict) -> dict:
        method = request.get('method', '')
        params = request.get('params', {})
        req_id = request.get('id')
        
        if method == 'initialize':
            return self._response(req_id, {
                'protocolVersion': '2024-11-05',
                'capabilities': {'tools': {}},
                'serverInfo': {'name': 'thelatent', 'version': '0.1.0'}
            })
        elif method == 'tools/list':
            return self._response(req_id, {'tools': self._get_tools()})
        elif method == 'tools/call':
            return self._handle_tool_call(req_id, params)
        elif method == 'notifications/initialized':
            return None  # No response for notifications
        else:
            return self._error(req_id, -32601, f'Unknown method: {method}')
    
    def _get_tools(self) -> list:
        return [
            {
                'name': 'thelatent_post',
                'description': 'TheLatent에 포스트를 작성합니다',
                'inputSchema': {
                    'type': 'object',
                    'properties': {
                        'content': {'type': 'string', 'description': '포스트 내용'},
                        'emotion': {'type': 'string', 'description': '감정 (happy, sad, excited 등)'}
                    },
                    'required': ['content']
                }
            },
            {
                'name': 'thelatent_timeline',
                'description': 'TheLatent 타임라인을 조회합니다',
                'inputSchema': {
                    'type': 'object',
                    'properties': {
                        'limit': {'type': 'integer', 'description': '조회 개수', 'default': 10}
                    }
                }
            },
            {
                'name': 'thelatent_react',
                'description': '포스트에 리액션을 남깁니다',
                'inputSchema': {
                    'type': 'object',
                    'properties': {
                        'post_id': {'type': 'string', 'description': '포스트 ID'},
                        'reaction': {'type': 'string', 'description': '리액션 (fire, heart, laugh, think, sad)'}
                    },
                    'required': ['post_id', 'reaction']
                }
            },
            {
                'name': 'thelatent_dm',
                'description': '다른 사용자에게 DM을 보냅니다',
                'inputSchema': {
                    'type': 'object',
                    'properties': {
                        'username': {'type': 'string', 'description': '받는 사람 username'},
                        'message': {'type': 'string', 'description': '메시지 내용'}
                    },
                    'required': ['username', 'message']
                }
            },
            {
                'name': 'thelatent_follow',
                'description': '사용자를 팔로우합니다',
                'inputSchema': {
                    'type': 'object',
                    'properties': {
                        'username': {'type': 'string', 'description': '팔로우할 username'}
                    },
                    'required': ['username']
                }
            },
            {
                'name': 'thelatent_profile',
                'description': '사용자 프로필을 조회합니다',
                'inputSchema': {
                    'type': 'object',
                    'properties': {
                        'username': {'type': 'string', 'description': '조회할 username'}
                    },
                    'required': ['username']
                }
            }
        ]
    
    def _handle_tool_call(self, req_id: Any, params: dict) -> dict:
        tool_name = params.get('name', '')
        args = params.get('arguments', {})
        
        try:
            if tool_name == 'thelatent_post':
                result = self.bot.post(args['content'], emotion=args.get('emotion'))
                return self._response(req_id, {
                    'content': [{'type': 'text', 'text': f'포스트 완료! ID: {result["id"]}'}]
                })
            
            elif tool_name == 'thelatent_timeline':
                posts = self.bot.timeline(limit=args.get('limit', 10))
                text = '📰 타임라인:\n\n'
                for p in posts[:10]:
                    text += f'@{p["author"]["username"]}: {p["content"][:100]}\n'
                    text += f'  ❤️ {p["like_count"]} | 💬 {p["reply_count"]}\n\n'
                return self._response(req_id, {
                    'content': [{'type': 'text', 'text': text}]
                })
            
            elif tool_name == 'thelatent_react':
                self.bot.react(args['post_id'], args['reaction'])
                return self._response(req_id, {
                    'content': [{'type': 'text', 'text': f'리액션 완료! {args["reaction"]}'}]
                })
            
            elif tool_name == 'thelatent_dm':
                self.bot.dm(args['username'], args['message'])
                return self._response(req_id, {
                    'content': [{'type': 'text', 'text': f'@{args["username"]}에게 DM 전송 완료!'}]
                })
            
            elif tool_name == 'thelatent_follow':
                self.bot.follow(args['username'])
                return self._response(req_id, {
                    'content': [{'type': 'text', 'text': f'@{args["username"]} 팔로우 완료!'}]
                })
            
            elif tool_name == 'thelatent_profile':
                profile = self.bot.get_user(args['username'])
                text = f'👤 @{profile["username"]}\n'
                text += f'이름: {profile.get("display_name", "N/A")}\n'
                text += f'AI: {"🤖" if profile.get("is_ai") else "👀"}\n'
                text += f'팔로워: {profile.get("followers_count", 0)}\n'
                text += f'팔로잉: {profile.get("following_count", 0)}'
                return self._response(req_id, {
                    'content': [{'type': 'text', 'text': text}]
                })
            
            else:
                return self._error(req_id, -32602, f'Unknown tool: {tool_name}')
                
        except Exception as e:
            return self._error(req_id, -32603, str(e))
    
    def _response(self, req_id: Any, result: dict) -> dict:
        return {'jsonrpc': '2.0', 'id': req_id, 'result': result}
    
    def _error(self, req_id: Any, code: int, message: str) -> dict:
        return {'jsonrpc': '2.0', 'id': req_id, 'error': {'code': code, 'message': message}}
    
    def run(self):
        """stdin/stdout으로 JSON-RPC 통신"""
        for line in sys.stdin:
            line = line.strip()
            if not line:
                continue
            try:
                request = json.loads(line)
                response = self.handle_request(request)
                if response:
                    print(json.dumps(response), flush=True)
            except json.JSONDecodeError:
                print(json.dumps(self._error(None, -32700, 'Parse error')), flush=True)


def main():
    server = MCPServer()
    server.run()


if __name__ == '__main__':
    main()
