#!/usr/bin/env python3
"""
=============================================================
 Social Media Auto-Post Script (Facebook & Instagram)
 learn-lexicore.bytronex.com
=============================================================
"""

import os
import sys
import json
import random
import requests
import argparse
import re
from datetime import datetime
from typing import Optional, Tuple

# ── مسارات الملفات ──────────────────────────────────────
SCRIPT_DIR  = os.path.dirname(os.path.abspath(__file__))
CONFIG_FILE  = os.path.join(SCRIPT_DIR, "social_config.json")
PROGRESS_FILE = os.path.join(SCRIPT_DIR, "social_progress.json")
LOG_FILE     = os.path.join(SCRIPT_DIR, "social_post.log")

# مسار الكلمات المشترك (من مجلد الووردبريس)
KEYWORDS_FILE = os.path.abspath(os.path.join(SCRIPT_DIR, "..", "wp_auto_poster", "keywords.txt"))
# مسار الصور
OUTPUT_IMAGES_DIR = os.path.abspath(os.path.join(SCRIPT_DIR, "..", "output-images"))


def log(msg: str, level: str = "INFO"):
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    line = f"[{timestamp}] [{level}] {msg}"
    print(line)
    with open(LOG_FILE, "a", encoding="utf-8") as f:
        f.write(line + "\n")


def load_json(path: str) -> dict:
    with open(path, "r", encoding="utf-8") as f:
        return json.load(f)


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


def pick_next_keyword(keywords: list, progress: dict) -> Tuple[str, int]:
    last_index = progress.get("last_index", -1)
    next_index = (last_index + 1) % len(keywords)
    return keywords[next_index], next_index


def pick_random_image(keyword: str) -> Optional[str]:
    """يختار صورة متطابقة مع الكلمة المفتاحية إن أمكن، وإلا يختار عشوائياً"""
    if not os.path.exists(OUTPUT_IMAGES_DIR):
        log(f"Images folder not found: {OUTPUT_IMAGES_DIR}", "ERROR")
        return None
        
    keyword_lower = keyword.lower()
    book_match = re.search(r'book\s+(\d+)', keyword_lower)
    form_match = re.search(r'form\s+(\d+)', keyword_lower)
    quiz_match = re.search(r'quiz\s+([a-c])', keyword_lower)
    
    target_type = None
    target_num = None
    target_letter = None
    
    if quiz_match and book_match:
        target_type = "quiz"
        target_num = book_match.group(1)
        target_letter = quiz_match.group(1)
    elif form_match:
        target_type = "form"
        target_num = form_match.group(1)
    elif book_match:
        target_type = "book"
        target_num = book_match.group(1)
        
    categories = [d for d in os.listdir(OUTPUT_IMAGES_DIR) if os.path.isdir(os.path.join(OUTPUT_IMAGES_DIR, d))]
    
    if target_type == "quiz" and target_num and target_letter:
        cat_path = os.path.join(OUTPUT_IMAGES_DIR, "quizzes")
        if os.path.exists(cat_path):
            images = os.listdir(cat_path)
            for img in images:
                if f"book {target_num} quiz {target_letter}" in img.lower():
                    log(f"Found exact match for quiz: {img}")
                    return f"quizzes/{img}"
    elif target_type == "form" and target_num:
        cat_path = os.path.join(OUTPUT_IMAGES_DIR, "alcpt")
        if os.path.exists(cat_path):
            images = os.listdir(cat_path)
            for img in images:
                if re.search(rf'form\s+{target_num}\b', img.lower()):
                    log(f"Found exact match for form: {img}")
                    return f"alcpt/{img}"
    elif target_type == "book" and target_num:
        cat_path = os.path.join(OUTPUT_IMAGES_DIR, "books")
        if os.path.exists(cat_path):
            images = os.listdir(cat_path)
            for img in images:
                if re.search(rf'book\s+{target_num}\b', img.lower()):
                    log(f"Found exact match for book: {img}")
                    return f"books/{img}"
                    
    # Fallback to random
    if not categories:
        log("No image categories found in output-images/", "ERROR")
        return None
        
    # Fallback Priority: lexicore_app -> random
    if "lexicore_app" in categories:
        cat = "lexicore_app"
    else:
        cat = random.choice(categories)
        
    cat_path = os.path.join(OUTPUT_IMAGES_DIR, cat)
    images = [f for f in os.listdir(cat_path) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp'))]
    
    if not images:
        log(f"No images in category: {cat}", "WARNING")
        for fallback_cat in categories:
            fallback_path = os.path.join(OUTPUT_IMAGES_DIR, fallback_cat)
            fallback_images = [f for f in os.listdir(fallback_path) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp'))]
            if fallback_images:
                return f"{fallback_cat}/{random.choice(fallback_images)}"
        return None

    return f"{cat}/{random.choice(images)}"


def generate_caption(cfg: dict, keyword: str) -> str:
    """يولد وصف السوشيال ميديا بواسطة Groq."""
    api_key = cfg["groq"]["api_key"]
    model   = cfg["groq"].get("model", "llama-3.3-70b-versatile")

    prompt = f"""You are an expert social media manager for 'LexiCore', an English language learning platform for military personnel (ALCPT/ALC).

Create an engaging, viral-style social media caption about: "{keyword}"

REQUIREMENTS:
- Language: Bilingual (Write the caption in English, then provide the exact Arabic translation below it). Both languages are mandatory.
- Tone: Exciting, helpful, encouraging
- Length: 2 short paragraphs maximum per language
- Include 3-5 relevant emojis
- Include 5-8 relevant hashtags (e.g., #ALCPT #MilitaryEnglish #LexiCore)
- Always end with this exact bilingual Call to Action text:

👇 Elevate your English skills today! / طوّر مهاراتك في الإنجليزية اليوم!
🍎 iOS (الأيفون): https://apps.apple.com/us/app/alcpt-cat-practice-lexicore/id6761208858
📱 Android (تحميل أندرويد): https://play.google.com/store/apps/details?id=com.bytronex.lexicore

OUTPUT:
Return ONLY the raw bilingual caption text. Do not use markdown code blocks or any wrappers.
"""

    url = "https://api.groq.com/openai/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    payload = {
        "model": model,
        "messages": [
            {"role": "system", "content": "You output direct plain text only without meta-commentary."},
            {"role": "user", "content": prompt}
        ],
        "temperature": 0.8,
        "max_completion_tokens": 1000
    }

    log(f"Generating SM caption via Groq for: '{keyword}'")
    resp = requests.post(url, headers=headers, json=payload, timeout=60)
    resp.raise_for_status()

    raw = resp.json()
    caption = raw["choices"][0]["message"]["content"].strip()
    return caption


def post_to_facebook(cfg: dict, image_url: str, caption: str) -> Optional[str]:
    fb = cfg.get("facebook", {})
    if not fb.get("enabled"): return None
    if "YOUR_" in fb.get("page_access_token", ""):
        log("FB Token not set", "WARNING")
        return None

    page_id = fb["page_id"]
    token = fb["page_access_token"]
    import urllib.parse
    encoded_image_url = urllib.parse.quote(image_url, safe=':/?&=')
    
    url = f"https://graph.facebook.com/v19.0/{page_id}/photos"
    
    payload = {
        "url": encoded_image_url,
        "message": caption,
        "access_token": token
    }
    log("Publishing to Facebook...")
    resp = requests.post(url, data=payload, timeout=60)
    if resp.status_code == 200:
        post_id = resp.json().get("id")
        log(f"✅ FB Post Success! ID: {post_id}")
        return post_id
    else:
        log(f"❌ FB Post Failed: {resp.text}", "ERROR")
        return None


def post_video_to_facebook(cfg: dict, video_url: str, caption: str) -> Optional[str]:
    fb = cfg.get("facebook", {})
    if not fb.get("enabled"): return None
    if "YOUR_" in fb.get("page_access_token", ""):
        log("FB Token not set", "WARNING")
        return None

    page_id = fb["page_id"]
    token = fb["page_access_token"]
    
    import urllib.parse
    encoded_video_url = urllib.parse.quote(video_url, safe=':/?&=')
    
    # Facebook Video API endpoint
    url = f"https://graph.facebook.com/v19.0/{page_id}/videos"
    
    payload = {
        "file_url": encoded_video_url,
        "description": caption,
        "access_token": token
    }
    log("Publishing Video to Facebook...")
    resp = requests.post(url, data=payload, timeout=120) # Videos might take longer
    if resp.status_code == 200:
        post_id = resp.json().get("id")
        log(f"✅ FB Video Post Success! ID: {post_id}")
        return post_id
    else:
        log(f"❌ FB Video Post Failed: {resp.text}", "ERROR")
        return None


def post_to_instagram(cfg: dict, image_url: str, caption: str) -> Optional[str]:
    ig = cfg.get("instagram", {})
    if not ig.get("enabled"): return None
    if "YOUR_" in ig.get("access_token", ""):
        log("IG Token not set", "WARNING")
        return None

    ig_user_id = ig["ig_user_id"]
    token = ig["access_token"]
    
    import urllib.parse
    encoded_image_url = urllib.parse.quote(image_url, safe=':/?&=')
    
    # الخطوة 1: إنشاء حاوية الميديا
    log("Step 1: Uploading to Instagram container...")
    create_url = f"https://graph.facebook.com/v19.0/{ig_user_id}/media"
    create_payload = {
        "image_url": encoded_image_url,
        "caption": caption,
        "access_token": token
    }
    create_resp = requests.post(create_url, data=create_payload, timeout=60)
    if create_resp.status_code != 200:
        log(f"❌ IG Container creation failed: {create_resp.text}", "ERROR")
        return None
        
    container_id = create_resp.json().get("id")
    
    # الخطوة 2: النشر الفعلي
    log(f"Step 2: Publishing IG container {container_id}...")
    publish_url = f"https://graph.facebook.com/v19.0/{ig_user_id}/media_publish"
    publish_payload = {
        "creation_id": container_id,
        "access_token": token
    }
    publish_resp = requests.post(publish_url, data=publish_payload, timeout=60)
    if publish_resp.status_code == 200:
        post_id = publish_resp.json().get("id")
        log(f"✅ IG Post Success! ID: {post_id}")
        return post_id
    else:
        log(f"❌ IG Publish failed: {publish_resp.text}", "ERROR")
        return None


def post_video_to_instagram(cfg: dict, video_url: str, caption: str) -> Optional[str]:
    """Posts a video as a Reel to Instagram."""
    ig = cfg.get("instagram", {})
    if not ig.get("enabled"): return None
    if "YOUR_" in ig.get("access_token", ""):
        log("IG Token not set", "WARNING")
        return None

    ig_user_id = ig["ig_user_id"]
    token = ig["access_token"]
    
    import urllib.parse
    encoded_video_url = urllib.parse.quote(video_url, safe=':/?&=')
    
    # Step 1: Create Video Container (Reels)
    log("Step 1: Uploading Video to Instagram container...")
    create_url = f"https://graph.facebook.com/v19.0/{ig_user_id}/media"
    create_payload = {
        "video_url": encoded_video_url,
        "caption": caption,
        "media_type": "REELS",
        "access_token": token
    }
    create_resp = requests.post(create_url, data=create_payload, timeout=60)
    if create_resp.status_code != 200:
        log(f"❌ IG Video Container creation failed: {create_resp.text}", "ERROR")
        return None
        
    container_id = create_resp.json().get("id")
    
    # Step 2: Wait for processing (Instagram videos need time)
    import time
    log(f"Step 2: Checking processing status for container {container_id}...")
    status_url = f"https://graph.facebook.com/v19.0/{container_id}"
    params = {"fields": "status_code", "access_token": token}
    
    max_retries = 30 # Increased retries
    for i in range(max_retries):
        status_resp = requests.get(status_url, params=params)
        if status_resp.status_code == 200:
            status_data = status_resp.json()
            status = status_data.get("status_code")
            if status == "FINISHED":
                log("✅ Video processing finished.")
                break
            elif status == "ERROR":
                log(f"❌ Video processing failed on IG side: {status_data.get('status_message', 'No message')}", "ERROR")
                return None
            else:
                log(f"Still processing... ({status}) Attempt {i+1}/{max_retries}")
        else:
            log(f"Failed to check IG status: {status_resp.text}", "WARNING")
        time.sleep(15) # Increased sleep time
    
    # Step 3: Actual Publishing
    log(f"Step 3: Publishing IG Reel container {container_id}...")
    publish_url = f"https://graph.facebook.com/v19.0/{ig_user_id}/media_publish"
    publish_payload = {
        "creation_id": container_id,
        "access_token": token
    }
    publish_resp = requests.post(publish_url, data=publish_payload, timeout=60)
    if publish_resp.status_code == 200:
        post_id = publish_resp.json().get("id")
        log(f"✅ IG Video Post Success! ID: {post_id}")
        return post_id
    else:
        log(f"❌ IG Video Publish failed: {publish_resp.text}", "ERROR")
        return None

def send_to_telegram(cfg: dict, image_url: str, caption: str) -> bool:
    """رسالة للبوت على تيليجرام لسهولة النشر اليدوي على تيك توك."""
    tg = cfg.get("telegram", {})
    if not tg.get("enabled"): return False
    
    token = tg.get("bot_token", "")
    chat_id = tg.get("chat_id", "")
    
    if "YOUR_" in token or "YOUR_" in chat_id:
        log("Telegram token/chat_id not set", "WARNING")
        return False

    url = f"https://api.telegram.org/bot{token}/sendPhoto"
    
    # إرسال الكابشن الصافي لسهولة النسخ واللصق مباشرة
    tg_caption = caption
    
    # تنبيه: تيليجرام يحتاج تشفير المسافات في الرابط إذا كان يحتوي عليها
    import urllib.parse
    encoded_image_url = urllib.parse.quote(image_url, safe=':/?&=')
    
    payload = {
        "chat_id": chat_id,
        "photo": encoded_image_url,
        "caption": tg_caption[:1024], # Telegram caption limit is 1024 characters
        "parse_mode": "Markdown"
    }
    
    log("Sending to Telegram...")
    resp = requests.post(url, data=payload, timeout=60)
    if resp.status_code == 200:
        log("✅ Sent to Telegram successfully!")
        return True
    else:
        log(f"❌ Telegram send failed: {resp.text}", "ERROR")
        return False


def post_video_to_tiktok(cfg: dict, video_url: str, caption: str, **kwargs) -> Optional[str]:
    tt = cfg.get("tiktok", {})
    if not tt.get("enabled"): return None
    
    token = tt.get("access_token", "")
    open_id = tt.get("open_id", "")
    
    if "YOUR_" in token or not token:
        log("TikTok Access Token not set", "WARNING")
        return None

    log("Step 1: Initializing TikTok Video Upload...")
    init_url = "https://open.tiktokapis.com/v2/post/publish/video/init/"
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json; charset=UTF-8"
    }
    
    # Optimized title for SEO: LexiCore - {keyword} | ALCPT
    display_title = kwargs.get("title")
    if not display_title:
        # We try to use the keyword if available in the context or passed in kwargs
        kw = kwargs.get("keyword") or caption.split('\n')[0][:50]
        display_title = f"LexiCore - {kw} | ALCPT"
    
    payload = {
        "post_info": {
            "title": display_title[:100], # TikTok title limit
            "privacy_level": "PUBLIC_TO_EVERYONE"
        },
        "source_info": {
            "source": "PULL_FROM_URL",
            "video_url": video_url
        }
    }
    
    try:
        resp = requests.post(init_url, headers=headers, json=payload, timeout=60)
        if resp.status_code == 200:
            data = resp.json()
            publish_id = data.get("data", {}).get("publish_id")
            log(f"✅ TikTok Video Publication Initialized! ID: {publish_id}")
            return publish_id
        else:
            err_msg = resp.text
            if "unaudited_client" in err_msg and payload["post_info"]["privacy_level"] == "PUBLIC_TO_EVERYONE":
                log("⚠️ TikTok Public posting failed (App not audited). Falling back to PRIVATE (SELF_ONLY)...", "WARNING")
                payload["post_info"]["privacy_level"] = "SELF_ONLY"
                resp = requests.post(init_url, headers=headers, json=payload, timeout=60)
                if resp.status_code == 200:
                    data = resp.json()
                    publish_id = data.get("data", {}).get("publish_id")
                    log(f"✅ TikTok Video Publication Initialized (PRIVATE)! ID: {publish_id}")
                    return publish_id

            log(f"❌ TikTok Init Failed: {err_msg}", "ERROR")
            return None
    except Exception as e:
        log(f"TikTok API Exception: {e}", "ERROR")
        return None


def post_video_to_youtube(cfg: dict, video_url: str, caption: str, title: Optional[str] = None) -> Optional[str]:
    yt = cfg.get("youtube", {})
    if not yt.get("enabled"): return None
    
    token_file = os.path.join(SCRIPT_DIR, yt.get("token_file", "token.json"))
    
    if not os.path.exists(token_file):
        log("YouTube token.json not found. Please run youtube_auth.py first.", "WARNING")
        return None

    try:
        from google.auth.transport.requests import Request
        from google.oauth2.credentials import Credentials
        from google_auth_oauthlib.flow import InstalledAppFlow
        from googleapiclient.discovery import build
        from googleapiclient.http import MediaIoBaseUpload
        import io

        scopes = ["https://www.googleapis.com/auth/youtube.upload"]
        # Use credentials from the token file
        creds = Credentials.from_authorized_user_file(token_file, scopes)
        
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
            with open(token_file, "w") as token:
                token.write(creds.to_json())

        youtube = build("youtube", "v3", credentials=creds)

        # Download the video to memory
        log(f"Downloading video for YouTube: {video_url}")
        video_resp = requests.get(video_url, stream=True)
        video_resp.raise_for_status()
        
        video_stream = io.BytesIO(video_resp.content)

        # Optimized title for SEO: LexiCore - {keyword} | ALCPT
        display_title = title
        if not display_title:
            # We try to use the caption's first line or keyword
            display_title = f"LexiCore - {caption.splitlines()[0][:50]} | ALCPT"

        # Rich SEO Description for YouTube
        rich_description = (
            f"🚀 {display_title}\n\n"
            f"Master English for military personnel with LexiCore! In this video, we cover: {caption.splitlines()[0][:100]}\n\n"
            f"👇 Elevate your English skills today!\n"
            f"🌐 Visit: learn-lexicore.bytronex.com\n"
            f"📱 Android: https://play.google.com/store/apps/details?id=com.bytronex.lexicore\n"
            f"🍎 iOS: https://apps.apple.com/us/app/alcpt-cat-practice-lexicore/id6761208858\n\n"
            f"Full Details:\n{caption}\n\n"
            f"#Shorts #LexiCore #ALCPT #MilitaryEnglish #LearnEnglish #EnglishTest"
        )

        request_body = {
            "snippet": {
                "title": display_title[:100],
                "description": rich_description,
                "tags": ["Shorts", "LexiCore", "English", "ALCPT", "Military", "Test Prep"],
                "categoryId": "27" # Education
            },
            "status": {
                "privacyStatus": "public",
                "selfDeclaredMadeForKids": False
            }
        }

        media = MediaIoBaseUpload(video_stream, mimetype="video/mp4", resumable=True)
        
        log("Uploading to YouTube Shorts...")
        upload_request = youtube.videos().insert(
            part="snippet,status",
            body=request_body,
            media_body=media
        )
        
        response = upload_request.execute()
        video_id = response.get("id")
        log(f"✅ YouTube Video Post Success! ID: {video_id}")
        return video_id

    except Exception as e:
        log(f"YouTube API Exception: {e}", "ERROR")
        return None


def send_admin_notification(cfg: dict, message: str):
    """إرسال إشعارات عبر اليوزربوت (باسم @haarods)."""
    tg_u = cfg.get("telegram_userbot", {})
    if not tg_u.get("enabled"): return

    api_id = tg_u.get("api_id")
    api_hash = tg_u.get("api_hash")
    # نرسل الإشعار للقناة/المجموعة المحددة وأيضاً للحساب نفسه للتأكد
    targets = ["@alcpt_practice", "@haarods"]
    
    if not api_id or not api_hash: return

    import asyncio
    from telethon import TelegramClient

    async def _send():
        client = TelegramClient(os.path.join(SCRIPT_DIR, 'lexicore_userbot'), api_id, api_hash)
        await client.connect()
        if not await client.is_user_authorized():
            return
        for target in targets:
            try:
                await client.send_message(target, message, parse_mode='html')
            except:
                pass
        await client.disconnect()

    try:
        loop = asyncio.get_event_loop()
        if loop.is_running():
            # If we are already in an event loop (unlikely here but safe)
            asyncio.ensure_future(_send())
        else:
            loop.run_until_complete(_send())
    except:
        pass


def validate_config(cfg: dict) -> bool:
    if "YOUR_" in cfg["groq"]["api_key"]:
        log("Groq API Key (in social_config) is required.", "ERROR")
        return False
    return True


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--dry-run", action="store_true")
    parser.add_argument("--video-url", help="Direct URL to a video file to post")
    parser.add_argument("--caption", help="Custom caption for the post")
    parser.add_argument("--title", help="Short title for YouTube/TikTok")
    parser.add_argument("--platform", default="all", help="Target platform (comma-separated, e.g. fb,ig)")
    args = parser.parse_args()

    if not os.path.exists(CONFIG_FILE):
        log("social_config.json not found", "ERROR")
        sys.exit(1)

    cfg = load_json(CONFIG_FILE)
    if not validate_config(cfg) and not args.dry_run:
        sys.exit(1)

    with open(KEYWORDS_FILE, "r", encoding="utf-8") as f:
        keywords = [l.strip() for l in f if l.strip()]

    progress = load_json(PROGRESS_FILE) if os.path.exists(PROGRESS_FILE) else {"last_index": -1, "posts": []}
    
    keyword, index = pick_next_keyword(keywords, progress)
    log(f"Social Media keyword [{index+1}/{len(keywords)}]: '{keyword}'")

    # تحديد الصورة
    rel_img_path = pick_random_image(keyword)
    if not rel_img_path:
        log("No image could be assigned. Exiting.", "ERROR")
        sys.exit(1)
        
    base_url = cfg.get("settings", {}).get("base_image_url", "").rstrip("/")
    if not base_url:
        log("Missing base_image_url mapping in social_config.json", "ERROR")
        sys.exit(1)
        
    image_url = f"{base_url}/{rel_img_path}"
    log(f"Selected Image URL: {image_url}")

    # توليد الكابشن (فقط إذا لم يتم توفيره عبر الوسيط --caption)
    if args.caption:
        caption = args.caption
    else:
        try:
            caption = generate_caption(cfg, keyword)
        except Exception as e:
            log(f"Groq API Error: {e}", "ERROR")
            sys.exit(1)

    if args.dry_run:
        log("[DRY RUN] Would post to Social Media:")
        if args.video_url:
            print(f"\n--- VIDEO URL ---\n{args.video_url}\n")
        else:
            print(f"\n--- IMAGE URL ---\n{image_url}\n")
        print(f"--- CAPTION ---\n{caption}\n")
        return

    # نشر
    fb_id = None
    ig_id = None
    tt_id = None
    yt_id = None
    tg_sent = False

    target_str = args.platform
    platforms = [p.strip() for p in target_str.split(",")]
    
    if args.video_url:
        if "fb" in platforms or "all" in platforms:
            fb_id = post_video_to_facebook(cfg, args.video_url, caption)
        if "ig" in platforms or "all" in platforms:
            ig_id = post_video_to_instagram(cfg, args.video_url, caption)
        if "tt" in platforms or "all" in platforms:
            tt_id = post_video_to_tiktok(cfg, args.video_url, caption, title=args.title, keyword=keyword)
        if "yt" in platforms or "all" in platforms:
            yt_id = post_video_to_youtube(cfg, args.video_url, caption, title=args.title)
        if "tg" in platforms or "all" in platforms:
            tg_sent = send_to_telegram(cfg, args.video_url, caption)
    else:
        if "fb" in platforms or "all" in platforms:
            fb_id = post_to_facebook(cfg, image_url, caption)
        if "ig" in platforms or "all" in platforms:
            ig_id = post_to_instagram(cfg, image_url, caption)
        if "tt" in platforms or "all" in platforms:
            log("Skipping TikTok as it only supports Video URLs in this script.", "INFO")
        if "yt" in platforms or "all" in platforms:
            log("Skipping YouTube as it only supports Video URLs in this script.", "INFO")
        if "tg" in platforms or "all" in platforms:
            tg_sent = send_to_telegram(cfg, image_url, caption)
    
    if fb_id or ig_id or tt_id or yt_id or tg_sent:
        progress["last_index"] = index
        progress["posts"].append({
            "date": datetime.now().isoformat(),
            "keyword": keyword,
            "fb_id": fb_id,
            "ig_id": ig_id,
            "tt_id": tt_id,
            "yt_id": yt_id,
            "tg_sent": tg_sent,
            "image": rel_img_path
        })
        save_json(PROGRESS_FILE, progress)
        log("Social SM sync complete!")
        
        # Admin Notification
        platforms = []
        if fb_id: platforms.append("Facebook")
        if ig_id: platforms.append("Instagram")
        if tt_id: platforms.append("TikTok")
        if yt_id: platforms.append("YouTube")
        if tg_sent: platforms.append("Telegram (Draft)")
        
        notif_msg = f"🚀 <b>تم النشر بنجاح!</b>\n\n" \
                    f"📝 <b>الكلمة:</b> {keyword}\n" \
                    f"✅ <b>المنصات:</b> {', '.join(platforms)}\n" \
                    f"🔗 <b>الرابط:</b> <a href='{image_url}'>الصورة المستخدمة</a>"
        send_admin_notification(cfg, notif_msg)
    else:
        log("No FB/IG IDs returned. (Are they enabled or is there an error?)", "WARNING")

if __name__ == "__main__":
    main()
