import os
import time
import threading
from functools import wraps
from flask import Flask, request, jsonify, render_template, redirect, url_for, session
from database import init_db, get_db, get_setting, set_setting
from engine import parse_telegram_link, run_pending_orders_sync

app = Flask(__name__)
app.secret_key = os.environ.get("FLASK_SECRET", "simoon_panel_ultra_secret_key_99")

init_db()

# --- احراز هویت پنل ادمین ---
def admin_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if not session.get("logged_in"):
            return redirect(url_for("login"))
        return f(*args, **kwargs)
    return decorated

@app.route("/login", methods=["GET", "POST"])
def login():
    error = None
    if request.method == "POST":
        if request.form.get("password") == get_setting("admin_password"):
            session["logged_in"] = True
            return redirect(url_for("admin_dashboard"))
        error = "رمز عبور اشتباه است."
    return f"""
    <html dir="rtl" lang="fa"><head><meta charset="utf-8"><title>ورود به پنل سین‌زن</title>
    <script src="https://cdn.tailwindcss.com"></script></head>
    <body class="bg-slate-900 text-white flex items-center justify-center h-screen">
      <form method="post" class="bg-slate-800 p-8 rounded-xl shadow-lg w-80 space-y-4">
        <h2 class="text-xl font-bold text-center">پنل مدیریت سین‌زن</h2>
        {"<p class='text-red-400 text-sm'>" + error + "</p>" if error else ""}
        <input type="password" name="password" placeholder="رمز عبور ادمین" class="w-full p-2 rounded bg-slate-700 text-white" required>
        <button class="w-full bg-blue-600 hover:bg-blue-700 py-2 rounded font-bold">ورود</button>
      </form>
    </body></html>
    """

@app.route("/logout")
def logout():
    session.clear()
    return redirect(url_for("login"))

# --- داشبورد مدیریت ---
@app.route("/")
@admin_required
def admin_dashboard():
    conn = get_db()
    orders = conn.execute("SELECT * FROM orders ORDER BY id DESC LIMIT 50").fetchall()
    proxies = conn.execute("SELECT * FROM proxies ORDER BY id DESC").fetchall()
    stats = conn.execute("""
        SELECT COUNT(*) as total_orders,
               COALESCE(SUM(sent), 0) as total_views,
               SUM(CASE WHEN status IN ('Pending', 'In progress') THEN 1 ELSE 0 END) as active_orders
        FROM orders
    """).fetchone()
    conn.close()

    settings = {
        "api_key": get_setting("api_key"),
        "cron_secret": get_setting("cron_secret"),
        "concurrency": get_setting("concurrency"),
        "overdelivery_ratio": get_setting("overdelivery_ratio"),
    }
    return render_template("admin.html", orders=orders, proxies=proxies, stats=stats, settings=settings)

@app.route("/admin/add_proxies", methods=["POST"])
@admin_required
def add_proxies():
    raw = request.form.get("proxies", "")
    lines = [l.strip() for l in raw.splitlines() if l.strip()]
    conn = get_db()
    for p in lines:
        conn.execute("INSERT OR IGNORE INTO proxies (proxy_url) VALUES (?)", (p,))
    conn.commit()
    conn.close()
    return redirect(url_for("admin_dashboard"))

@app.route("/admin/clear_proxies", methods=["POST"])
@admin_required
def clear_proxies():
    conn = get_db()
    conn.execute("DELETE FROM proxies")
    conn.commit()
    conn.close()
    return redirect(url_for("admin_dashboard"))

@app.route("/admin/settings", methods=["POST"])
@admin_required
def update_settings():
    for key in ["api_key", "concurrency", "overdelivery_ratio", "cron_secret"]:
        if request.form.get(key):
            set_setting(key, request.form.get(key).strip())
    if request.form.get("new_password"):
        set_setting("admin_password", request.form.get("new_password").strip())
    return redirect(url_for("admin_dashboard"))

@app.route("/admin/manual_order", methods=["POST"])
@admin_required
def manual_order():
    link = request.form.get("link", "")
    qty = int(request.form.get("quantity", 100))
    channel, post_id = parse_telegram_link(link)
    if channel and post_id:
        conn = get_db()
        conn.execute(
            "INSERT INTO orders (link, channel, post_id, quantity, source) VALUES (?, ?, ?, ?, 'Admin')",
            (link, channel, post_id, qty)
        )
        conn.commit()
        conn.close()
    return redirect(url_for("admin_dashboard"))

# --- نقطه اجرای کرون‌جاب (مخصوص هاست اشتراکی) ---
@app.route("/cron/process")
def cron_process():
    if request.args.get("secret") != get_setting("cron_secret"):
        return jsonify({"error": "Invalid secret"}), 403
    sent = run_pending_orders_sync(batch_limit=150)
    return jsonify({"status": "ok", "views_sent_in_batch": sent})

# --- API استاندارد SMM v2 (برای اتصال به ssimoon.com و ربات مجیک سین) ---
@app.route("/api/v2", methods=["POST", "GET"])
def smm_api_v2():
    data = request.form if request.method == "POST" else request.args
    api_key = data.get("key")
    action = data.get("action")

    if api_key != get_setting("api_key"):
        return jsonify({"error": "Invalid API key"}), 401

    if action == "balance":
        return jsonify({"balance": "999999.00", "currency": "USD"})

    elif action == "services":
        price = get_setting("service_price_per_1k", "0.05")
        return jsonify([
            {
                "service": 1,
                "name": "Telegram Post Views [Public Channels - Fast]",
                "type": "Default",
                "category": "Telegram Views",
                "rate": price,
                "min": "10",
                "max": "500000"
            }
        ])

    elif action == "add":
        link = data.get("link", "")
        try:
            quantity = int(data.get("quantity", 0))
        except ValueError:
            return jsonify({"error": "Invalid quantity"}), 400

        channel, post_id = parse_telegram_link(link)
        if not channel or not post_id:
            return jsonify({"error": "Invalid Telegram public post link"}), 400
        if quantity < 10:
            return jsonify({"error": "Minimum quantity is 10"}), 400

        source = data.get("source", "ssimoon_api")
        conn = get_db()
        cur = conn.execute(
            "INSERT INTO orders (link, channel, post_id, quantity, source) VALUES (?, ?, ?, ?, ?)",
            (link, channel, post_id, quantity, source)
        )
        order_id = cur.lastrowid
        conn.commit()
        conn.close()
        return jsonify({"order": order_id})

    elif action == "status":
        order_id = data.get("order")
        conn = get_db()
        row = conn.execute("SELECT * FROM orders WHERE id = ?", (order_id,)).fetchone()
        conn.close()
        if not row:
            return jsonify({"error": "Order not found"}), 404

        remains = max(0, row["quantity"] - row["sent"])
        return jsonify({
            "charge": "0.00",
            "start_count": "0",
            "status": row["status"],
            "remains": str(remains),
            "currency": "USD"
        })

    return jsonify({"error": "Invalid action"}), 400

# --- ورکر پس‌زمینه (فقط روی سرور اختصاصی فعال شود) ---
def start_background_worker():
    def loop():
        while True:
            try:
                run_pending_orders_sync(batch_limit=300)
            except Exception:
                pass
            time.sleep(3)
    t = threading.Thread(target=loop, daemon=True)
    t.start()

if __name__ == "__main__":
    # در حالت اجرای مستقیم روی سرور اختصاصی، ورکر خودکار روشن می‌شود
    start_background_worker()
    app.run(host="0.0.0.0", port=5000)