import urllib.request
import re
import json
import os
import sqlite3
import time
import xml.etree.ElementTree as ET
from concurrent.futures import ThreadPoolExecutor

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATA_DIR = os.path.join(BASE_DIR, "data")
os.makedirs(DATA_DIR, exist_ok=True)
JSON_FILE = os.path.join(DATA_DIR, "apps.json")
DB_FILE = os.path.join(DATA_DIR, "store.db")

def init_db():
    conn = sqlite3.connect(DB_FILE)
    c = conn.cursor()
    c.execute('''
        CREATE TABLE IF NOT EXISTS apps (
            id TEXT PRIMARY KEY,
            slug TEXT UNIQUE,
            name TEXT,
            subtitle TEXT,
            category TEXT,
            type TEXT DEFAULT 'game',
            description TEXT,
            version TEXT,
            file_size TEXT,
            ios_version TEXT,
            rating REAL DEFAULT 4.8,
            rating_count TEXT DEFAULT '2.4K',
            developer TEXT,
            icon_url TEXT,
            screenshots TEXT,
            ipa_download_url TEXT,
            livecontainer_url TEXT,
            is_featured INTEGER DEFAULT 0,
            is_trending INTEGER DEFAULT 0,
            is_offline INTEGER DEFAULT 0,
            date_published TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    ''')
    conn.commit()
    return conn

def get_game_urls(max_urls=60):
    print("Fetching sitemap from ipagame.store...")
    req = urllib.request.Request("https://ipagame.store/sitemap.xml", headers={"User-Agent": "Mozilla/5.0"})
    try:
        with urllib.request.urlopen(req, timeout=15) as resp:
            xml_data = resp.read()
        root = ET.fromstring(xml_data)
        urls = []
        for child in root:
            if len(child) > 0:
                loc = child[0].text
                if not loc:
                    continue
                parts = [p for p in loc.split('/') if p]
                # Match https://ipagame.store/ipa-games/<category>/<game-slug>
                if len(parts) == 5 and parts[2] in ('ipa-games', 'ipa-apps'):
                    urls.append(loc)
        print(f"Found {len(urls)} game item URLs.")
        # Pick diverse selection across categories
        selected = urls[:max_urls]
        return selected
    except Exception as e:
        print(f"Error fetching sitemap: {e}")
        return []

def scrape_single_app(url):
    try:
        req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)"})
        with urllib.request.urlopen(req, timeout=12) as resp:
            html = resp.read().decode('utf-8', errors='ignore')

        # Extract slug
        slug = url.strip('/').split('/')[-1]
        
        # Schema LD+JSON
        schema_matches = re.findall(r'<script type="application/ld\+json">(.*?)</script>', html, re.DOTALL)
        app_data = {}
        for sm in schema_matches:
            try:
                data = json.loads(sm.strip())
                if data.get('@type') == 'SoftwareApplication':
                    app_data = data
                    break
            except:
                pass

        if not app_data:
            return None

        name = app_data.get('name', slug.replace('-ipa', '').replace('-', ' ').title())
        category = app_data.get('applicationSubCategory', 'Action')
        ios_version = app_data.get('operatingSystem', 'iOS 15.0+')
        version = app_data.get('softwareVersion', '1.0.0')
        file_size = app_data.get('fileSize', '50 MB')
        icon_url = app_data.get('image', '')
        screenshots = app_data.get('screenshot', [])
        developer = "Apple Developer"
        author = app_data.get('author')
        if isinstance(author, dict):
            developer = author.get('name', developer)

        # Meta description
        desc_match = re.search(r'<meta name="description" content="(.*?)">', html)
        description = desc_match.group(1) if desc_match else f"Download {name} IPA file for iOS."

        # Extract detailed paragraphs if available
        detail_paragraphs = re.findall(r'<p>(.*?)</p>', html)
        if len(detail_paragraphs) > 3:
            cleaned_p = [re.sub(r'<[^>]+>', '', p) for p in detail_paragraphs if len(p) > 50 and 'cookie' not in p.lower() and 'javascript' not in p.lower()]
            if cleaned_p:
                description = "\n\n".join(cleaned_p[:3])

        # Rating
        rating = 4.8
        rating_match = re.search(r'<b>([\d\.]+)\s*<span class="stars"', html)
        if rating_match:
            try:
                rating = float(rating_match.group(1))
            except:
                pass

        rating_count = "2.5K"
        rc_match = re.search(r'<small>([\d\.]+[KM]?\s*ratings?)</small>', html, re.IGNORECASE)
        if rc_match:
            rating_count = rc_match.group(1)

        item = {
            "id": slug,
            "slug": slug,
            "name": name,
            "subtitle": f"{category} for iOS",
            "category": category,
            "type": "game",
            "description": description,
            "version": version,
            "fileSize": file_size,
            "iosVersion": ios_version,
            "rating": rating,
            "ratingCount": rating_count,
            "developer": developer,
            "iconUrl": icon_url,
            "screenshots": screenshots if isinstance(screenshots, list) else [screenshots],
            "ipaDownloadUrl": f"https://archive.org/download/{slug}/{slug}.ipa", # direct link format / mirror
            "livecontainerUrl": f"livecontainer://install?url=https://archive.org/download/{slug}/{slug}.ipa",
            "isFeatured": 1 if rating >= 4.9 else 0,
            "isTrending": 1 if "cod" in slug or "efootball" in slug or "gta" in slug or "subway" in slug else 0,
            "isOffline": 1 if "offline" in html.lower() else 0,
            "datePublished": app_data.get('datePublished', '2026-11-01')
        }
        print(f"Scraped: {name} ({category}) - {version}")
        return item
    except Exception as e:
        print(f"Error scraping {url}: {e}")
        return None

def main():
    conn = init_db()
    c = conn.cursor()
    
    urls = get_game_urls(max_urls=40)
    print(f"Starting scrape of {len(urls)} apps...")
    
    scraped_items = []
    with ThreadPoolExecutor(max_workers=5) as executor:
        results = executor.map(scrape_single_app, urls)
        for res in results:
            if res:
                scraped_items.append(res)
                
                # Insert or update in SQLite
                c.execute('''
                    INSERT OR REPLACE INTO apps (
                        id, slug, name, subtitle, category, type, description,
                        version, file_size, ios_version, rating, rating_count,
                        developer, icon_url, screenshots, ipa_download_url,
                        livecontainer_url, is_featured, is_trending, is_offline,
                        date_published
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ''', (
                    res['id'], res['slug'], res['name'], res['subtitle'], res['category'],
                    res['type'], res['description'], res['version'], res['fileSize'],
                    res['iosVersion'], res['rating'], res['ratingCount'], res['developer'],
                    res['iconUrl'], json.dumps(res['screenshots']), res['ipaDownloadUrl'],
                    res['livecontainerUrl'], res['isFeatured'], res['isTrending'],
                    res['isOffline'], res['datePublished']
                ))
    
    conn.commit()
    conn.close()
    
    # Also save to JSON
    with open(JSON_FILE, 'w', encoding='utf-8') as f:
        json.dump(scraped_items, f, indent=2, ensure_ascii=False)
        
    print(f"\nSUCCESS! Scraped and saved {len(scraped_items)} items to {JSON_FILE} and {DB_FILE}")

if __name__ == '__main__':
    main()
