#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Flirty Telegram Bot - Python Version for FTP Server
"""

import os
import json
import logging
from datetime import datetime
from pathlib import Path

# Конфигурация
TOKEN = "8712806454:AAGOJWV24VYM8zbpgr7HlZ40glFjWmujAog"
BOT_NAME = "Алиса"
DATA_DIR = Path("./conversations")

# Настройка логирования
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO
)
logger = logging.getLogger(__name__)

class FlirtyBotFTP:
    def __init__(self):
        self.data_dir = DATA_DIR
        self.data_dir.mkdir(exist_ok=True)
        print(f"🤖 Flirty Bot {BOT_NAME} initialized")
        print(f"📁 Data directory: {self.data_dir.absolute()}")
        
    def save_message(self, user_id, role, text):
        """Сохраняет сообщение в историю"""
        user_file = self.data_dir / f"user_{user_id}.json"
        
        if user_file.exists():
            with open(user_file, 'r', encoding='utf-8') as f:
                data = json.load(f)
        else:
            data = {
                "user_id": user_id,
                "conversations": [],
                "first_seen": datetime.now().isoformat(),
                "flirt_level": 0
            }
        
        data["conversations"].append({
            "role": role,
            "text": text,
            "timestamp": datetime.now().isoformat()
        })
        
        # Храним только последние 100 сообщений
        if len(data["conversations"]) > 100:
            data["conversations"] = data["conversations"][-100:]
        
        with open(user_file, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        
        return data
    
    def generate_response(self, user_message):
        """Генерирует кокетливый ответ"""
        import random
        
        msg = user_message.lower()
        
        # Приветствия
        if any(word in msg for word in ["привет", "хай", "здравствуй", "hello"]):
            greetings = [
                "Привет, солнышко! 🌞 Как твой день?",
                "О, а вот и ты! Я уже начала скучать... 😊",
                "Приветик! Ты где пропадал?"
            ]
            return random.choice(greetings)
        
        # Вопросы о делах
        if any(word in msg for word in ["как дела", "как ты", "how are you"]):
            responses = [
                "Отлично! Особенно когда ты пишешь! 💕",
                "Прекрасно! А у тебя как? 😊",
                "Супер! Ты делаешь мой день лучше! 🌟"
            ]
            return random.choice(responses)
        
        # Случайные ответы
        responses = [
            "Расскажи что-нибудь интересное! 💬",
            "Как прошел твой день?",
            "О чем мечтаешь?",
            "Что нового?",
            "Мне нравится с тобой общаться! 😊",
            "Ты такой интересный собеседник! 💖",
            "Продолжай, мне нравится! 🌟"
        ]
        return random.choice(responses)
    
    def test(self):
        """Тестовая функция"""
        print("🧪 Running test...")
        
        test_user = "test_123"
        test_msg = "Привет, как дела?"
        
        # Сохраняем тестовое сообщение
        data = self.save_message(test_user, "user", test_msg)
        print(f"📝 Saved user message: {test_msg}")
        
        # Генерируем ответ
        response = self.generate_response(test_msg)
        print(f"💬 Generated response: {response}")
        
        # Сохраняем ответ бота
        self.save_message(test_user, "bot", response)
        
        # Показываем историю
        user_file = self.data_dir / f"user_{test_user}.json"
        if user_file.exists():
            with open(user_file, 'r', encoding='utf-8') as f:
                history = json.load(f)
            print(f"📊 Total messages: {len(history['conversations'])}")
        
        print("✅ Test completed successfully!")

if __name__ == "__main__":
    bot = FlirtyBotFTP()
    bot.test()
