from flask import Flask, request, render_template_string

app = Flask(__name__)

API_KEY = "sk-uwEKiIuWlzlpeop4F3gLgw5JQQ0T9oanQefg86nZZdK47o4l"
API_URL = "https://api.gapgpt.app/v1/chat/completions"

HTML = '''
<!DOCTYPE html>
<html dir="rtl" lang="fa">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>هوش مصنوعی | GapGPT</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, sans-serif;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
            background: #0a0a12;
            position: relative;
            overflow-x: hidden;
        }

        .ai-bg {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 0;
            background: 
                radial-gradient(ellipse at 20% 30%, rgba(0, 212, 255, 0.08), transparent 50%),
                radial-gradient(ellipse at 80% 70%, rgba(138, 43, 226, 0.08), transparent 50%),
                radial-gradient(ellipse at 50% 50%, rgba(0, 0, 0, 0.9), transparent 70%),
                linear-gradient(135deg, #0a0a12 0%, #1a0a2e 30%, #0a1a2e 60%, #0a0a12 100%);
            animation: bgMove 15s ease-in-out infinite alternate;
        }

        @keyframes bgMove {
            0% {
                background: radial-gradient(ellipse at 20% 30%, rgba(0, 212, 255, 0.1), transparent 50%),
                            radial-gradient(ellipse at 80% 70%, rgba(138, 43, 226, 0.1), transparent 50%),
                            radial-gradient(ellipse at 50% 50%, rgba(0, 0, 0, 0.9), transparent 70%),
                            linear-gradient(135deg, #0a0a12 0%, #1a0a2e 30%, #0a1a2e 60%, #0a0a12 100%);
            }
            50% {
                background: radial-gradient(ellipse at 30% 40%, rgba(0, 212, 255, 0.12), transparent 50%),
                            radial-gradient(ellipse at 70% 60%, rgba(138, 43, 226, 0.12), transparent 50%),
                            radial-gradient(ellipse at 50% 50%, rgba(0, 0, 0, 0.9), transparent 70%),
                            linear-gradient(135deg, #0a0a12 0%, #2a0a3e 30%, #0a2a3e 60%, #0a0a12 100%);
            }
            100% {
                background: radial-gradient(ellipse at 40% 50%, rgba(0, 212, 255, 0.1), transparent 50%),
                            radial-gradient(ellipse at 60% 50%, rgba(138, 43, 226, 0.1), transparent 50%),
                            radial-gradient(ellipse at 50% 50%, rgba(0, 0, 0, 0.9), transparent 70%),
                            linear-gradient(135deg, #0a0a12 0%, #1a0a3e 30%, #0a2a3e 60%, #0a0a12 100%);
            }
        }

        .particles {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 0;
            pointer-events: none;
            overflow: hidden;
        }

        .particle {
            position: absolute;
            width: 2px;
            height: 2px;
            background: rgba(0, 212, 255, 0.4);
            border-radius: 50%;
            animation: floatParticle linear infinite;
            box-shadow: 0 0 6px rgba(0, 212, 255, 0.2);
        }

        @keyframes floatParticle {
            0% { transform: translateY(100vh) scale(0); opacity: 0; }
            10% { opacity: 1; transform: translateY(90vh) scale(1); }
            90% { opacity: 1; }
            100% { transform: translateY(-10vh) scale(0); opacity: 0; }
        }

        .glow-rings {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 0;
            pointer-events: none;
            overflow: hidden;
        }

        .ring {
            position: absolute;
            border-radius: 50%;
            border: 1px solid rgba(0, 212, 255, 0.04);
            animation: ringFloat 20s ease-in-out infinite;
        }

        .ring:nth-child(1) {
            width: 400px;
            height: 400px;
            top: -100px;
            right: -100px;
            animation-delay: 0s;
        }
        .ring:nth-child(2) {
            width: 600px;
            height: 600px;
            bottom: -200px;
            left: -150px;
            border-color: rgba(138, 43, 226, 0.04);
            animation-delay: -5s;
        }
        .ring:nth-child(3) {
            width: 300px;
            height: 300px;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            border-color: rgba(0, 255, 200, 0.03);
            animation-delay: -10s;
        }

        @keyframes ringFloat {
            0%, 100% { transform: translate(0, 0) rotate(0deg); }
            33% { transform: translate(20px, -30px) rotate(120deg); }
            66% { transform: translate(-20px, 20px) rotate(240deg); }
        }

        .container {
            position: relative;
            z-index: 1;
            max-width: 750px;
            width: 100%;
            background: rgba(0, 0, 0, 0.55);
            backdrop-filter: blur(16px);
            border-radius: 28px;
            padding: 35px 30px;
            border: 1px solid rgba(0, 212, 255, 0.08);
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
        }

        .header {
            text-align: center;
            margin-bottom: 25px;
        }

        .header .icon {
            display: block;
            margin: 0 auto 10px;
            width: 70px;
            height: 70px;
        }

        .header .icon img {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }

        .header h1 {
            font-size: 28px;
            font-weight: 800;
            background: linear-gradient(90deg, #00d4ff, #8a2be2, #00ff88);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
        }

        .header p {
            color: #888;
            font-size: 14px;
            margin-top: 4px;
        }

        .divider {
            width: 60px;
            height: 2px;
            background: linear-gradient(90deg, transparent, #00d4ff, transparent);
            margin: 12px auto 0;
            border-radius: 2px;
        }

        .chat-box {
            background: rgba(0, 0, 0, 0.35);
            border-radius: 16px;
            padding: 16px;
            height: 380px;
            overflow-y: auto;
            margin-bottom: 16px;
            border: 1px solid rgba(255, 255, 255, 0.04);
            display: flex;
            flex-direction: column;
        }

        .msg {
            padding: 10px 16px;
            border-radius: 16px;
            margin-bottom: 10px;
            max-width: 85%;
            word-wrap: break-word;
            font-size: 14px;
            line-height: 1.6;
        }

        .user {
            background: linear-gradient(135deg, #00d4ff, #0088cc);
            color: #0a0a12;
            align-self: flex-end;
            border-bottom-right-radius: 4px;
        }

        .bot {
            background: rgba(255, 255, 255, 0.06);
            color: #e0e0e0;
            align-self: flex-start;
            border-bottom-left-radius: 4px;
            border-left: 2px solid #00d4ff;
        }

        .typing {
            color: #666;
            font-size: 13px;
            padding: 8px 14px;
            align-self: flex-start;
        }

        .input-area {
            display: flex;
            gap: 10px;
        }

        .input-area input {
            flex: 1;
            padding: 12px 16px;
            border-radius: 14px;
            border: 1px solid rgba(255, 255, 255, 0.06);
            background: rgba(0, 0, 0, 0.3);
            color: #fff;
            font-size: 15px;
            outline: none;
            transition: 0.3s;
        }

        .input-area input:focus {
            border-color: #00d4ff;
            box-shadow: 0 0 20px rgba(0, 212, 255, 0.05);
        }

        .input-area input::placeholder {
            color: #555;
        }

        .input-area button {
            padding: 12px 28px;
            border: none;
            border-radius: 14px;
            font-size: 15px;
            font-weight: 700;
            cursor: pointer;
            background: linear-gradient(135deg, #00d4ff, #8a2be2);
            color: #fff;
            transition: 0.3s;
        }

        .input-area button:hover {
            opacity: 0.85;
            transform: scale(1.02);
        }

        .input-area button:active {
            transform: scale(0.96);
        }

        .footer {
            text-align: center;
            margin-top: 18px;
            font-size: 11px;
            color: #444;
        }

        .footer span {
            color: #00d4ff;
        }

        .chat-box::-webkit-scrollbar {
            width: 4px;
        }

        .chat-box::-webkit-scrollbar-track {
            background: rgba(255, 255, 255, 0.02);
            border-radius: 10px;
        }

        .chat-box::-webkit-scrollbar-thumb {
            background: #00d4ff;
            border-radius: 10px;
        }

        @media (max-width: 600px) {
            .container { padding: 25px 18px; }
            .header h1 { font-size: 22px; }
            .chat-box { height: 280px; }
            .header .icon { width: 55px; height: 55px; }
        }
    </style>
</head>
<body>

    <div class="ai-bg"></div>

    <div class="glow-rings">
        <div class="ring"></div>
        <div class="ring"></div>
        <div class="ring"></div>
    </div>

    <div class="particles" id="particles"></div>

    <div class="container">
        <div class="header">
            <span class="icon">
                <img src="https://cdn.imgurl.ir/uploads/l288079_ChatGPT_Image______.png" alt="AI Icon">
            </span>
            <h1>هوش مصنوعی GapGPT</h1>
            <p>پرسش‌های خود را با هوش مصنوعی در میان بگذارید</p>
            <div class="divider"></div>
        </div>

        <div class="chat-box" id="chatBox">
            <div class="msg bot">سلام 👋 من هوش مصنوعی GapGPT هستم. هر سوالی داری بپرس!</div>
        </div>

        <div class="input-area">
            <input type="text" id="userInput" placeholder="پیام خود را بنویسید..." autofocus>
            <button onclick="sendMessage()">ارسال</button>
        </div>

        <div class="footer">
            🤖 GapGPT | ساخته شده با ❤️ | <span>COD_LUIZ</span>
        </div>
    </div>

    <script>
        const chatBox = document.getElementById('chatBox');
        const userInput = document.getElementById('userInput');

        function addMessage(text, type) {
            const div = document.createElement('div');
            div.className = 'msg ' + type;
            div.textContent = text;
            chatBox.appendChild(div);
            chatBox.scrollTop = chatBox.scrollHeight;
        }

        function showTyping() {
            const div = document.createElement('div');
            div.className = 'typing';
            div.id = 'typing';
            div.textContent = '🧠 در حال فکر کردن...';
            chatBox.appendChild(div);
            chatBox.scrollTop = chatBox.scrollHeight;
        }

        function hideTyping() {
            const el = document.getElementById('typing');
            if (el) el.remove();
        }

        async function sendMessage() {
            const text = userInput.value.trim();
            if (!text) return;

            addMessage(text, 'user');
            userInput.value = '';
            showTyping();

            try {
                const res = await fetch('/ask', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ prompt: text })
                });

                const data = await res.json();
                hideTyping();

                if (data.error) {
                    addMessage('❌ ' + data.error, 'bot');
                } else {
                    addMessage(data.reply, 'bot');
                }
            } catch (e) {
                hideTyping();
                addMessage('❌ خطا در ارتباط با سرور', 'bot');
            }
        }

        userInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') sendMessage();
        });

        const particlesContainer = document.getElementById('particles');
        for (let i = 0; i < 50; i++) {
            const particle = document.createElement('div');
            particle.classList.add('particle');
            particle.style.left = Math.random() * 100 + '%';
            particle.style.animationDuration = (Math.random() * 20 + 10) + 's';
            particle.style.animationDelay = (Math.random() * 15) + 's';
            particle.style.width = (Math.random() * 3 + 1) + 'px';
            particle.style.height = particle.style.width;
            particlesContainer.appendChild(particle);
        }
    </script>
</body>
</html>
'''

@app.route('/')
def index():
    return render_template_string(HTML)

@app.route('/ask', methods=['POST'])
def ask():
    import requests
    import json

    data = request.json
    prompt = data.get('prompt', '')

    if not prompt:
        return {'error': 'متن وارد نشده است'}

    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }

    payload = {
        "model": "gpt-3.5-turbo",
        "messages": [{"role": "user", "content": prompt}],
        "temperature": 0.7
    }

    try:
        response = requests.post(API_URL, headers=headers, json=payload, timeout=30)
        response.raise_for_status()
        result = response.json()
        reply = result["choices"][0]["message"]["content"]
        return {'reply': reply}
    except Exception as e:
        return {'error': str(e)}

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5001, debug=True)  # ✅ پورت به ۵۰۰۱ تغییر کرد