#!/usr/bin/env python3
"""Simple database to track posted deals across platforms."""
import json
import os
import hashlib
from datetime import datetime

DB_FILE = os.path.join(os.path.dirname(__file__), "posted_deals.json")

def load_db():
    if os.path.exists(DB_FILE):
        with open(DB_FILE, 'r') as f:
            return json.load(f)
    return {}

def save_db(db):
    with open(DB_FILE, 'w') as f:
        json.dump(db, f, indent=2)

def check_posted(deal_id, platform):
    """Check if a deal has been posted to a platform."""
    db = load_db()
    key = f"{deal_id}_{platform}"
    return key in db

def record_post(deal_id, platform, post_id=None, url=None, deal_title="", dispensary=""):
    """Record that a deal was posted to a platform."""
    db = load_db()
    key = f"{deal_id}_{platform}"
    db[key] = {
        "deal_id": deal_id,
        "platform": platform,
        "post_id": post_id,
        "url": url,
        "deal_title": deal_title,
        "dispensary": dispensary,
        "posted_at": datetime.now().isoformat()
    }
    save_db(db)
    print(f"Recorded {deal_id} for {platform}")

def init_db():
    """Initialize the database file if it doesn't exist."""
    if not os.path.exists(DB_FILE):
        save_db({})
        print(f"Initialized database at {DB_FILE}")

def generate_deal_hash(deal):
    """Generate a unique hash for a deal."""
    deal_str = json.dumps(deal, sort_keys=True)
    return hashlib.md5(deal_str.encode()).hexdigest()[:12]

# CLI interface for backward compatibility
if __name__ == "__main__":
    import sys
    if len(sys.argv) < 3:
        print("Usage: posted_db.py check <deal_id> <platform>")
        print("       posted_db.py record <deal_id> <platform> [post_id] [url]")
        sys.exit(1)
    
    cmd = sys.argv[1]
    deal_id = sys.argv[2]
    
    if cmd == "check":
        if len(sys.argv) < 4:
            print("Usage: posted_db.py check <deal_id> <platform>")
            sys.exit(1)
        platform = sys.argv[3]
        posted = check_posted(deal_id, platform)
        print("POSTED:YES" if posted else "POSTED:NO")
    elif cmd == "record":
        if len(sys.argv) < 4:
            print("Usage: posted_db.py record <deal_id> <platform> [post_id] [url]")
            sys.exit(1)
        platform = sys.argv[3]
        post_id = sys.argv[4] if len(sys.argv) > 4 else None
        url = sys.argv[5] if len(sys.argv) > 5 else None
        record_post(deal_id, platform, post_id, url)
    else:
        print(f"Unknown command: {cmd}")
        sys.exit(1)
