from flask import Flask, request, jsonify
import threading
import time
import json
import gzip
import io
from seleniumwire import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
import base64

app = Flask(__name__)

chrome_options = Options()
#chrome_options.add_argument("--headless=new")
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument(r"user-data-dir=C:\\Users\\mahdideveloper2\\AppData\\Local\\Google\\Chrome\\User Data")
chrome_options.add_argument(r"profile-directory=Default")
chrome_options.binary_location = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"
service = Service('C:/batchscraper/chromedriver.exe', port=9013)


def decode_response_body(response):
    try:
        encoding = response.headers.get('Content-Encoding', '')
        body = response.body
        if 'gzip' in encoding:
            with gzip.GzipFile(fileobj=io.BytesIO(body)) as f:
                return f.read().decode('utf-8')
        return body.decode('utf-8')
    except:
        return ""

def check_batch(batch_id, result_container,video):

    username = "nova06bug10"
    password = "@LicenseMarket"
    credentials = f"{username}:{password}"
    auth_header = "Basic " + base64.b64encode(credentials.encode()).decode()


    driver = webdriver.Chrome(service=service, options=chrome_options)

    # ✨ تضمینی: ست کردن هدر برای همه‌ی درخواست‌ها
    def interceptor(request):
        if "hailuoai.fastpass-panel.ir/auth" in request.url:
            request.headers['Authorization'] = auth_header

    driver.request_interceptor = interceptor

    try:
        driver.get("https://hailuoai.fastpass-panel.ir/auth")
        time.sleep(2)
        # driver.get("https://nova06bug10:@<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>/create")
        # time.sleep(2)

        seen_requests = set()

        for _ in range(60):
            driver.refresh()
            time.sleep(5)

            for req in driver.requests:
                if req.id in seen_requests:
                    continue
                seen_requests.add(req.id)

                if req.response and req.method == 'GET' and "/v3/api/multimodal/video/my/batchCursor" in req.url:
                    body = decode_response_body(req.response)
                    try:
                        data = json.loads(body)
                        batches = data.get("data", {}).get("batchVideos", [])
                        for batch in batches:
                            print(video)
                            if video == 1 :
                                assets = batch.get("assets", [])
                                print(assets[0]['batchID'])
                                if str(assets[0]['batchID']) == str(batch_id):
                                    valid_images = []
                                    for asset in assets:
                                        cover = asset.get("coverURL")
                                        download = asset.get("downloadURL")
                                        if cover and download:
                                            valid_images.append({
                                                "coverURL": cover,
                                                "downloadURL": download
                                            })
                            else:
                                if str(batch.get("batchID")) == str(batch_id):
                                    assets = batch.get("assets", [])
                                    valid_images = []
                                    for asset in assets:
                                        cover = asset.get("coverURL")
                                        download = asset.get("downloadURL")
                                        if cover and download:
                                            valid_images.append({
                                                "coverURL": cover,
                                                "downloadURL": download
                                            })

                            if valid_images:
                                result_container["status"] = "ready"
                                result_container["images"] = valid_images
                                result_container["assets"] = assets
                                driver.quit()
                                return
                    except Exception as e:
                        print("خطا در پردازش:", e)
                        continue

        result_container["status"] = "timeout"
        driver.quit()

    except Exception as e:
        print("خطای اصلی:", e)
        result_container["status"] = "error"
        driver.quit()

@app.route('/check-batch', methods=['POST'])
def check_batch_route():
    data = request.json
    print(data)

    batch_id = data.get('batch_id')
    video = data.get('video')
    print(video)
    if video:
        video = 1
    else :
        video = 0
    if not batch_id:
        return jsonify({"error": "batch_id is required"}), 400

    result_container = {}
    t = threading.Thread(target=check_batch, args=(batch_id, result_container , video))
    t.start()
    t.join(timeout=360)  # نهایتاً ۶ دقیقه

    if "status" not in result_container:
        return jsonify({"status": "timeout"}), 504

    return jsonify(result_container)

if __name__ == '__main__':
    app.run(debug=True, host="0.0.0.0", port=6021)

local variable 'valid_images' referenced before assignment
چرا این خطا رو میده