import os
import json
import time
import datetime
import requests
import re

STATE_DIR = os.path.dirname(os.path.abspath(__file__))
STORE_STATE_FILE = os.path.join(STATE_DIR, "sbox_store_state.json")
CLOTHING_STATE_FILE = os.path.join(STATE_DIR, "sbox_clothing_state.json")

THREAD_ID = "1554339360533389348"
WEBHOOK_URL = f"https://discord.com/api/webhooks/1554337516298174514/fRIZSc20O2bRiETvt9nncPLhAWEUQbb3_gPXFUVy4WjHtrAFnXTkDnRmEIgfHDY4f0Og?thread_id={THREAD_ID}"

def load_json(path):
    if os.path.exists(path):
        try:
            with open(path, "r", encoding="utf-8") as f:
                return json.load(f)
        except Exception:
            return {}
    return {}

def save_json(path, data):
    with open(path, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=2)

def post_discord(embed):
    payload = {
        "username": "s&box Item & Skin Store Tracker",
        "avatar_url": "https://apps.sacredservers.ca/banners/sbox-loot.png",
        "embeds": [embed]
    }
    try:
        r = requests.post(WEBHOOK_URL, json=payload, timeout=10)
        return r.status_code in [200, 204]
    except Exception as e:
        print(f"Failed to post to Discord: {e}")
        return False

def check_steam_store():
    url = "https://store.steampowered.com/itemstore/590830/browse/?l=english"
    try:
        r = requests.get(url, headers={"User-Agent": "Mozilla/5.0"}, timeout=12)
        if r.status_code != 200:
            print(f"Steam store returned {r.status_code}")
            return
    except Exception as e:
        print(f"Error fetching Steam store: {e}")
        return

    html = r.text
    raw_items = re.findall(r'<div class="item_def_grid_item.*?(?=<div class="item_def_grid_item|\Z)', html, re.DOTALL)
    
    current_store = {}
    for it in raw_items:
        link_m = re.search(r'href="([^"]+)"', it)
        img_m = re.search(r'<img[^>]+src="([^"]+)"', it)
        name_m = re.search(r'class="item_def_name[^"]*"[^>]*><a[^>]*>(.*?)</a>', it, re.DOTALL)
        price_m = re.search(r'class="item_def_price"[^>]*>\s*([^\s<][^<]*?)\s*</div>', it, re.DOTALL)

        link = link_m.group(1) if link_m else "https://store.steampowered.com/itemstore/590830/"
        img = img_m.group(1) if img_m else ""
        name = name_m.group(1).strip() if name_m else "Unknown Item"
        price = price_m.group(1).strip() if price_m else "N/A"

        m = re.search(r'/detail/(\d+)', link)
        item_id = m.group(1) if m else name

        current_store[item_id] = {
            "id": item_id,
            "name": name,
            "price": price,
            "img": img,
            "link": link
        }

    previous_store = load_json(STORE_STATE_FILE)

    # First run initialization: do not blast all existing items if initial state is empty
    if not previous_store:
        print(f"Seeding store state with {len(current_store)} existing items (silent mode).")
        save_json(STORE_STATE_FILE, current_store)
        return

    # Check for new items or price adjustments
    for item_id, item in current_store.items():
        if item_id not in previous_store:
            print(f"✨ NEW STORE ITEM DETECTED: {item['name']} ({item['price']})")
            embed = {
                "title": f"🛍️ New s&box Skin Added: {item['name']}",
                "description": f"A brand new cosmetic skin has just arrived on the **official s&box Steam Item Store**!",
                "url": item["link"],
                "color": 0x2ECC71, # Bright Green
                "thumbnail": {
                    "url": item["img"]
                },
                "image": {
                    "url": item["img"]
                },
                "fields": [
                    {"name": "💵 Price", "value": f"`{item['price']}`", "inline": True},
                    {"name": "🆔 Def ID", "value": f"`{item['id']}`", "inline": True},
                    {"name": "🎮 Platform", "value": "`Steam Item Store`", "inline": True},
                    {"name": "🛒 Purchase / Inspect", "value": f"[Open in Steam Store]({item['link']})", "inline": False}
                ],
                "footer": {
                    "text": f"s&box Item Store Watcher • AppID 590830 • {datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%d %H:%M:%S')} UTC",
                    "icon_url": "https://apps.sacredservers.ca/banners/sbox-loot.png"
                }
            }
            post_discord(embed)
            time.sleep(1)
        else:
            old_item = previous_store[item_id]
            if old_item.get("price") != item["price"]:
                print(f"🏷️ PRICE CHANGE DETECTED: {item['name']} from {old_item.get('price')} to {item['price']}")
                embed = {
                    "title": f"🏷️ s&box Skin Price Update: {item['name']}",
                    "description": f"Price adjusted on the Steam Item Store for **{item['name']}**.",
                    "url": item["link"],
                    "color": 0xF39C12, # Orange
                    "thumbnail": {
                        "url": item["img"]
                    },
                    "fields": [
                        {"name": "📉 Previous Price", "value": f"`{old_item.get('price', 'N/A')}`", "inline": True},
                        {"name": "📈 New Price", "value": f"`{item['price']}`", "inline": True},
                        {"name": "🆔 Def ID", "value": f"`{item['id']}`", "inline": True},
                        {"name": "🛒 View Item", "value": f"[Open in Steam Store]({item['link']})", "inline": False}
                    ],
                    "footer": {
                        "text": f"s&box Store Watcher • {datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%d %H:%M:%S')} UTC",
                        "icon_url": "https://apps.sacredservers.ca/banners/sbox-loot.png"
                    }
                }
                post_discord(embed)
                time.sleep(1)

    # Save updated state
    save_json(STORE_STATE_FILE, current_store)

def check_clothing_packages():
    # Facepunch API requires query param 'q=type:clothing' to filter by package type
    url = "https://public.facepunch.com/sbox/package/find/2?q=type:clothing&order=newest&take=20"
    try:
        r = requests.get(url, headers={"User-Agent": "sbox/1.0.0.0"}, timeout=10)
        if r.status_code != 200:
            return
        data = r.json()
    except Exception as e:
        print(f"Error fetching clothing packages: {e}")
        return

    packages = data.get("Packages", [])
    current_clothing = {}
    for p in packages:
        # Explicitly verify package is clothing to guarantee games/maps are NEVER alerted as cosmetics
        if (p.get("TypeName") or "").lower() != "clothing":
            continue
        ident = p.get("FullIdent")
        if ident:
            current_clothing[ident] = {
                "ident": ident,
                "title": p.get("Title", ident),
                "org": p.get("Org", {}).get("Title", "Unknown Studio"),
                "summary": p.get("Summary", ""),
                "thumb": p.get("Thumb", ""),
                "updated": p.get("Updated", "")
            }

    previous_clothing = load_json(CLOTHING_STATE_FILE)

    if not previous_clothing:
        print(f"Seeding clothing state with {len(current_clothing)} packages (silent mode).")
        save_json(CLOTHING_STATE_FILE, current_clothing)
        return

    for ident, pkg in current_clothing.items():
        if ident not in previous_clothing:
            print(f"👕 NEW CLOTHING RELEASE: {pkg['title']} by {pkg['org']}")
            embed = {
                "title": f"👕 New s&box Cosmetic Asset: {pkg['title']}",
                "description": pkg["summary"] or f"New clothing piece published by **{pkg['org']}** for citizen & human avatars.",
                "url": f"https://asset.party/{ident}",
                "color": 0x9B59B6, # Purple
                "thumbnail": {
                    "url": pkg["thumb"] or "https://apps.sacredservers.ca/banners/sbox-loot.png"
                },
                "fields": [
                    {"name": "🏢 Creator Studio", "value": f"`{pkg['org']}`", "inline": True},
                    {"name": "📦 Package Ident", "value": f"`{ident}`", "inline": True},
                    {"name": "🌐 Asset Party", "value": f"[View 3D Model & Textures](https://asset.party/{ident})", "inline": False}
                ],
                "footer": {
                    "text": f"s&box Community Cosmetics • {datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%d %H:%M:%S')} UTC",
                    "icon_url": "https://apps.sacredservers.ca/banners/sbox-loot.png"
                }
            }
            post_discord(embed)
            time.sleep(1)

    save_json(CLOTHING_STATE_FILE, current_clothing)

def main():
    print(f"[{datetime.datetime.now(datetime.timezone.utc).strftime('%H:%M:%S')}] Polling s&box Store & Clothing additions...")
    check_steam_store()
    check_clothing_packages()
    print("Cycle complete.")

if __name__ == "__main__":
    main()
