import requests
import tarfile
import io
import os
import subprocess
import json

url = 'https://stabad.ir/stabad_bot_update.tar.gz'
dest_dir = '/home/in8wswn/StAbadServer_Bot'

print("Downloading...")
r = requests.get(url, verify=False, timeout=120)
print(f"Status: {r.status_code}, Size: {len(r.content)}")

if r.status_code != 200:
    print(json.dumps({"status": "error", "message": f"Download failed: {r.status_code}"}))
    exit()

# Extract from memory
print("Extracting...")
os.makedirs(dest_dir, exist_ok=True)
with tarfile.open(fileobj=io.BytesIO(r.content), mode='r:gz') as tar:
    tar.extractall(dest_dir)
    print(f"Extracted {len(tar.getnames())} files")

# Create .env
env_content = """BOT_TOKEN=8422026608:AAH0USRSN_sH4qPHv4wWNPYrG0e7g4XneOE
ADMIN_IDS=6512422794
OWNER_IDS=6512422794
DATABASE_URL=sqlite+aiosqlite:///data/stabad_bot.sqlite3
MINECRAFT_SERVER_HOST=Play.StAbad.ir
MINECRAFT_SERVER_PORT=25565
SERVER_NAME=StAbad
SERVER_WEBSITE=https://StAbad.ir
SERVER_DISCORD=https://StAbad.ir/discord
SERVER_TELEGRAM_CHANNEL=https://t.me/StAbad
SERVER_TELEGRAM_GROUP=https://t.me/Stabad_Group
"""
with open(os.path.join(dest_dir, '.env'), 'w') as f:
    f.write(env_content)
print(".env created")

# Create venv and install
venv_dir = dest_dir + '_venv'
if not os.path.exists(venv_dir):
    subprocess.run(['python3', '-m', 'venv', venv_dir], check=True)
    print("Venv created")

subprocess.run([os.path.join(venv_dir, 'bin', 'pip'), 'install', '-q', '-r', os.path.join(dest_dir, 'requirements.txt')], check=True)
print("Deps installed")

# Create webhook.php
webhook_content = '''<?php
header("Content-Type: application/json");
$update = json_decode(file_get_contents("php://input"), true);
if ($update) {
    $dataDir = __DIR__ . "/data/";
    if (!is_dir($dataDir)) mkdir($dataDir, 0755, true);
    file_put_contents($dataDir . "updates.json", json_encode($update, JSON_UNESCAPED_UNICODE) . "\n", FILE_APPEND | LOCK_EX);
}
echo json_encode(["ok" => true]);
'''
with open(os.path.join(dest_dir, 'webhook.php'), 'w') as f:
    f.write(webhook_content)
print("webhook.php created")

# Set webhook
webhook_url = 'https://stabad.s2026h.space/StAbadServer_Bot/webhook.php'
bot_token = '8422026608:AAH0USRSN_sH4qPHv4wWNPYrG0e7g4XneOE'
r = requests.post(f'https://api.telegram.org/bot{bot_token}/setWebhook', 
                  data={'url': webhook_url, 'drop_pending_updates': True}, 
                  verify=False)
print(f"Webhook set: {r.json()}")

print(json.dumps({"status": "success", "dir": dest_dir, "webhook": r.json()}))
