from fastapi import APIRouter, Request, Form, Depends
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
from app.database import get_db
from app.models.api_keys import UserPlatformKey
from app.auth.jwt_handler import get_optional_user_id
from app.crypto import encrypt_value
from app.config import PLATFORMS

router = APIRouter()
templates = Jinja2Templates(directory="templates")

# Per-platform instruction data (rich version for documentation pages)
PLATFORM_INSTRUCTIONS = {

    # ─────────────────────── TELEGRAM ────────────────────────
    "telegram": {
        "requirements": [
            "Telegram Account",
            "Telegram App (desktop or mobile)",
            "my.telegram.org access (for personal session)",
        ],
        "quick_steps": [
            "Open BotFather on Telegram",
            "Create a new bot with /newbot",
            "Copy your Bot Token",
            "Add bot to your group/channel",
            "Paste token into our platform",
        ],
        "detailed_steps": [
            {
                "title": "Step 1 — Get Your API ID & API Hash (Personal Session)",
                "desc": "Go to <a href='https://my.telegram.org' target='_blank'>my.telegram.org</a> and log in with your Telegram phone number. Navigate to <b>API Development Tools</b> and create a new application. Copy your <code>API ID</code> and <code>API Hash</code>.",
                "link": "https://my.telegram.org",
                "link_label": "Go to my.telegram.org",
                "tip": "This allows our platform to post to any group you are a member of — no bot required.",
                "warn": None,
                "screenshot_hint": "my.telegram.org API Development Tools page showing API ID and API Hash fields",
            },
            {
                "title": "Step 2 — Create a Bot using BotFather (Bot API Method)",
                "desc": "Open Telegram and search for <b>@BotFather</b>. Send the command <code>/newbot</code>. Choose a name and a username ending in <code>bot</code>. BotFather will give you a <b>Bot Token</b> that looks like: <code>123456789:AABBCCddEEff...</code>",
                "link": "https://t.me/BotFather",
                "link_label": "Open BotFather on Telegram",
                "tip": None,
                "warn": "Keep your Bot Token private. Anyone with this token can send messages as your bot.",
                "screenshot_hint": "BotFather chat showing /newbot command and token being provided",
            },
            {
                "title": "Step 3 — Add Your Bot to a Group or Channel",
                "desc": "Open your Telegram group or channel settings. Tap <b>Add Members</b> and search for your bot by username. Add it. For channels, give the bot <b>Admin</b> rights so it can post.",
                "link": None,
                "link_label": None,
                "tip": "If your bot cannot send messages, check that it has been added as an administrator to the channel.",
                "warn": None,
                "screenshot_hint": "Telegram group settings showing bot added as a member/admin",
            },
            {
                "title": "Step 4 — Find Your Chat ID",
                "desc": "Send a message in your group/channel then open this URL in your browser (replace TOKEN): <code>https://api.telegram.org/bot&lt;TOKEN&gt;/getUpdates</code>. Look for <code>chat.id</code> in the JSON response. Group IDs start with a <code>-</code> like <code>-100123456789</code>.",
                "link": "https://t.me/userinfobot",
                "link_label": "Or message @userinfobot for your personal chat ID",
                "tip": "For our platform's group posting feature, you don't need a chat ID — we fetch your groups automatically.",
                "warn": None,
                "screenshot_hint": "Browser showing getUpdates JSON response with chat.id highlighted",
            },
            {
                "title": "Step 5 — Set API ID and Hash in Your .env File",
                "desc": "Open your platform's <code>.env</code> file and add:<br><code>TELEGRAM_API_ID=12345678</code><br><code>TELEGRAM_API_HASH=abcdef1234567890abcdef1234567890</code><br>Restart the platform for the changes to take effect.",
                "link": None,
                "link_label": None,
                "tip": "After setting these, restart the server and the Telethon session will initialize automatically.",
                "warn": None,
                "screenshot_hint": ".env file with TELEGRAM_API_ID and TELEGRAM_API_HASH filled in",
            },
        ],
        "api_key_label": "Bot Token (optional — for bot-based posting)",
        "api_key_placeholder": "123456789:AABBccDDeeFFggHH...",
        "secret_key_label": None,
        "extra_label": "Chat ID (group/channel ID, e.g. -100123456789)",
        "extra_placeholder": "-100123456789",
        "doc_url": "https://core.telegram.org/bots/api",
        "doc_label": "Official Telegram Bot API Docs",
        "errors": [
            {
                "problem": "Unauthorized (401) — Bot token is invalid",
                "solution": "Double-check that you copied the full Bot Token from BotFather. It should look like <code>123456789:AABBCCddEEff...</code>",
            },
            {
                "problem": "Chat not found — Wrong Chat ID",
                "solution": "Make sure the bot has been added to the group/channel, and the chat ID is correct (groups start with <code>-</code>).",
            },
            {
                "problem": "Telethon session not starting — Missing API credentials",
                "solution": "Set <code>TELEGRAM_API_ID</code> and <code>TELEGRAM_API_HASH</code> in your <code>.env</code> file and restart the server.",
            },
            {
                "problem": "Message too long — Content exceeds 4096 characters",
                "solution": "Telegram has a 4096 character limit per message. Split your content into multiple messages.",
            },
        ],
        "video_search": "Telegram BotFather create bot and get token tutorial 2024",
    },

    # ─────────────────────── LINKEDIN ────────────────────────
    "linkedin": {
        "requirements": [
            "LinkedIn Account",
            "LinkedIn Developer App",
            "Share on LinkedIn Product enabled",
        ],
        "quick_steps": [
            "Go to LinkedIn Developer Portal",
            "Create a new Application",
            "Add Share on LinkedIn product",
            "Click Login with LinkedIn below",
            "Token saves automatically",
        ],
        "detailed_steps": [
            {
                "title": "Step 1 — Create a LinkedIn Developer Account",
                "desc": "Go to <a href='https://developer.linkedin.com/' target='_blank'>developer.linkedin.com</a> and sign in with your LinkedIn account. Click <b>Create App</b>. Fill in the App Name (e.g., 'My Automation'), choose a LinkedIn Page, and upload a logo.",
                "link": "https://developer.linkedin.com/",
                "link_label": "Go to LinkedIn Developer Portal",
                "tip": "You need a LinkedIn Page (company page) to create a developer app — create a free one if you don't have one.",
                "warn": None,
                "screenshot_hint": "LinkedIn developer portal showing Create App button and form fields",
            },
            {
                "title": "Step 2 — Add the Required Products",
                "desc": "Inside your app, go to the <b>Products</b> tab. Find and request access to: <b>Share on LinkedIn</b> and <b>Sign In with LinkedIn using OpenID Connect</b>. Click <b>Request Access</b> for each. Some are approved instantly.",
                "link": None,
                "link_label": None,
                "tip": "Make sure both products are approved (they show a green checkmark) before generating tokens.",
                "warn": None,
                "screenshot_hint": "LinkedIn app Products tab showing Share on LinkedIn with approved status",
            },
            {
                "title": "Step 3 — Set OAuth Redirect URL",
                "desc": "Go to the <b>Auth</b> tab. Under <b>OAuth 2.0 Settings</b>, add the Redirect URL: <code>http://localhost:8000/linkedin/callback</code>. Save changes. Also note your <b>Client ID</b> and <b>Client Secret</b> from this page.",
                "link": None,
                "link_label": None,
                "tip": None,
                "warn": "The redirect URL must exactly match what is set in your .env file (LINKEDIN_REDIRECT_URI).",
                "screenshot_hint": "LinkedIn app Auth tab showing redirect URL field and Client ID/Secret",
            },
            {
                "title": "Step 4 — Set Client ID & Secret in .env",
                "desc": "Open your <code>.env</code> file and set:<br><code>LINKEDIN_CLIENT_ID=your_client_id</code><br><code>LINKEDIN_CLIENT_SECRET=your_client_secret</code><br><code>LINKEDIN_REDIRECT_URI=http://localhost:8000/linkedin/callback</code>",
                "link": None,
                "link_label": None,
                "tip": "After saving .env, restart the platform server.",
                "warn": None,
                "screenshot_hint": ".env file with LinkedIn credentials filled in correctly",
            },
            {
                "title": "Step 5 — Authorize Via OAuth (Click the Button)",
                "desc": "Once your .env is set, click the blue <b>Login with LinkedIn & Get Token</b> button. You'll be redirected to LinkedIn's login page. Approve access. You'll be redirected back and your token will be saved automatically.",
                "link": None,
                "link_label": None,
                "tip": "Tokens expire in 60 days. Simply click the Login button again to refresh.",
                "warn": None,
                "screenshot_hint": "LinkedIn OAuth consent screen asking for permissions",
            },
        ],
        "api_key_label": None,
        "api_key_placeholder": None,
        "secret_key_label": None,
        "extra_label": None,
        "extra_placeholder": None,
        "doc_url": "https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin",
        "doc_label": "Official LinkedIn Share API Docs",
        "errors": [
            {
                "problem": "REVOKED_ACCESS_TOKEN — Token has expired",
                "solution": "LinkedIn tokens expire after 60 days. Click the <b>Login with LinkedIn</b> button again to get a fresh token.",
            },
            {
                "problem": "403 Forbidden — Missing permissions",
                "solution": "Make sure you added the <b>Share on LinkedIn</b> product and it has been approved on your developer app.",
            },
            {
                "problem": "invalid_redirect_uri — Redirect URL mismatch",
                "solution": "Your <code>LINKEDIN_REDIRECT_URI</code> in .env must exactly match what is saved in the LinkedIn app Auth tab.",
            },
            {
                "problem": "Member not found — Wrong Person URN",
                "solution": "Our platform fetches your Person URN automatically. If you see this error, re-authorize via the Login button.",
            },
        ],
        "video_search": "LinkedIn developer app OAuth 2.0 access token tutorial 2024",
    },

    # ─────────────────────── TWITTER / X ────────────────────────
    "twitter": {
        "requirements": [
            "Twitter / X Account",
            "Developer Account (Free tier OK)",
            "App with Read & Write permissions",
        ],
        "quick_steps": [
            "Go to Twitter Developer Portal",
            "Create a Project and App",
            "Enable OAuth 1.0a (Read & Write)",
            "Copy API Key, Secret, Access Token, Access Token Secret",
            "Paste credentials below",
        ],
        "detailed_steps": [
            {
                "title": "Step 1 — Apply for a Twitter Developer Account",
                "desc": "Go to <a href='https://developer.twitter.com/en/portal/dashboard' target='_blank'>developer.twitter.com</a> and sign in. If prompted, describe your use case (e.g., 'Personal automation tool to schedule posts'). Free tier accounts are approved instantly.",
                "link": "https://developer.twitter.com/en/portal/dashboard",
                "link_label": "Go to Twitter Developer Portal",
                "tip": "You do NOT need to pay for API access to post tweets from your own account. Free tier is sufficient.",
                "warn": None,
                "screenshot_hint": "Twitter Developer Portal dashboard showing Projects & Apps section",
            },
            {
                "title": "Step 2 — Create a Project and App",
                "desc": "Click <b>+ New Project</b>. Give it a name and use case. Then create a new <b>App</b> inside the project. Choose a unique app name.",
                "link": None,
                "link_label": None,
                "tip": None,
                "warn": "Make sure to select your app environment as 'Production' not 'Development' for it to work reliably.",
                "screenshot_hint": "Twitter app creation form with name and environment fields",
            },
            {
                "title": "Step 3 — Enable OAuth 1.0a with Read & Write",
                "desc": "Inside your app, go to <b>Settings → User Authentication Settings</b>. Enable <b>OAuth 1.0a</b>. Set permissions to <b>Read and Write</b>. Set the callback URL to <code>http://localhost</code>. Save.",
                "link": None,
                "link_label": None,
                "tip": None,
                "warn": "If you only enable Read permissions, posting tweets will return a 403 Forbidden error.",
                "screenshot_hint": "Twitter app settings showing OAuth 1.0a enabled with Read Write permissions",
            },
            {
                "title": "Step 4 — Copy API Keys and Tokens",
                "desc": "Go to <b>Keys and Tokens</b> tab. Copy:<br>• <b>API Key</b> (Consumer Key)<br>• <b>API Secret</b> (Consumer Secret)<br>Then click <b>Generate</b> under Access Token and Secret. Copy:<br>• <b>Access Token</b><br>• <b>Access Token Secret</b>",
                "link": None,
                "link_label": None,
                "tip": "Save these keys immediately — the Access Token Secret is shown only once.",
                "warn": None,
                "screenshot_hint": "Twitter Keys and Tokens tab showing all four credential fields",
            },
            {
                "title": "Step 5 — Paste Credentials into Our Platform",
                "desc": "In the form on the right, paste your <b>API Key</b> and <b>API Secret</b>. In the Extra JSON field, paste:<br><code>{\"access_token\": \"your_access_token\", \"access_token_secret\": \"your_access_token_secret\"}</code>",
                "link": None,
                "link_label": None,
                "tip": "Use double quotes in the JSON. Single quotes will cause a parsing error.",
                "warn": None,
                "screenshot_hint": "Our platform connect form with all Twitter credentials pasted in",
            },
        ],
        "api_key_label": "API Key (Consumer Key)",
        "api_key_placeholder": "aZbYcXdWeV...",
        "secret_key_label": "API Secret (Consumer Secret)",
        "extra_label": 'Extra JSON: {"access_token": "...", "access_token_secret": "..."}',
        "extra_placeholder": '{"access_token": "12345-abc...", "access_token_secret": "xyz..."}',
        "doc_url": "https://developer.twitter.com/en/docs/twitter-api",
        "doc_label": "Official Twitter / X API Docs",
        "errors": [
            {
                "problem": "89 — Invalid or expired token",
                "solution": "Your Access Token is invalid. Go to the Twitter Developer Portal → Keys and Tokens → regenerate Access Token & Secret.",
            },
            {
                "problem": "403 Forbidden — Write permission denied",
                "solution": "Your app only has Read permissions. Go to Settings → User Authentication Settings and change to <b>Read and Write</b>. Then regenerate tokens.",
            },
            {
                "problem": "187 — Status is a duplicate",
                "solution": "Twitter does not allow posting the same tweet twice. Change your post content slightly.",
            },
            {
                "problem": "Free plan rate limit — Too many requests",
                "solution": "The free Twitter API plan allows limited posts per month. Upgrade to a paid plan for higher limits.",
            },
        ],
        "video_search": "Twitter X developer API OAuth 1.0a get API keys access token tutorial 2024",
    },

    # ─────────────────────── REDDIT ────────────────────────
    "reddit": {
        "requirements": [
            "Reddit Account",
            "Verified Email on Reddit",
            "Reddit Developer App (Script Type)",
        ],
        "quick_steps": [
            "Go to reddit.com/prefs/apps",
            "Create a new 'script' type app",
            "Copy Client ID and Client Secret",
            "Add your Reddit username and password to JSON",
            "Paste credentials below",
        ],
        "detailed_steps": [
            {
                "title": "Step 1 — Go to Reddit App Preferences",
                "desc": "Log in to Reddit and go to <a href='https://www.reddit.com/prefs/apps' target='_blank'>reddit.com/prefs/apps</a>. Scroll to the bottom and click <b>Create another app...</b> (or 'Create App' if it's your first time).",
                "link": "https://www.reddit.com/prefs/apps",
                "link_label": "Go to Reddit App Preferences",
                "tip": "Make sure your Reddit account email is verified before creating apps.",
                "warn": None,
                "screenshot_hint": "Reddit preferences apps page showing Create Another App button",
            },
            {
                "title": "Step 2 — Create a Script Type App",
                "desc": "Fill in the form:<br>• <b>Name</b>: Any name (e.g., 'MyAutomation')<br>• <b>App type</b>: Select <b>script</b><br>• <b>Redirect URI</b>: <code>http://localhost</code><br>Click <b>Create app</b>.",
                "link": None,
                "link_label": None,
                "tip": "The 'script' type is for personal use automation — perfect for this platform.",
                "warn": "Do NOT select 'web app' or 'installed app' — those require OAuth redirects and are more complex.",
                "screenshot_hint": "Reddit create app form with 'script' type selected",
            },
            {
                "title": "Step 3 — Copy Client ID and Client Secret",
                "desc": "After creating the app, you'll see it listed. The <b>Client ID</b> is the short string shown directly below your app name (under 'personal use script'). The <b>Client Secret</b> is labelled 'secret'.",
                "link": None,
                "link_label": None,
                "tip": "The Client ID is usually 14-15 characters. The Client Secret is longer. Copy both carefully.",
                "warn": None,
                "screenshot_hint": "Reddit app listing showing Client ID below app name and Secret field",
            },
            {
                "title": "Step 4 — Prepare Your Extra JSON Credentials",
                "desc": "In the Extra JSON field in our form, provide your Reddit login details and the target subreddit:<br><code>{</code><br>&nbsp;&nbsp;<code>\"username\": \"your_reddit_username\",</code><br>&nbsp;&nbsp;<code>\"password\": \"your_reddit_password\",</code><br>&nbsp;&nbsp;<code>\"subreddit\": \"test\",</code><br>&nbsp;&nbsp;<code>\"title\": \"Default post title\"</code><br><code>}</code>",
                "link": None,
                "link_label": None,
                "tip": "The subreddit field should be without the r/ prefix — just the name such as 'test' or 'programming'.",
                "warn": None,
                "screenshot_hint": "Our platform form with extra JSON field filled with Reddit credentials",
            },
            {
                "title": "Step 5 — Create a User Agent String",
                "desc": "Reddit's API requires a user agent. Our platform generates one for you automatically based on your app name. If you need a custom one, the format is: <code>platform:appname:v1.0 (by /u/yourusername)</code>",
                "link": "https://www.reddit.com/dev/api/",
                "link_label": "Reddit API Documentation",
                "tip": "A proper user agent helps Reddit identify your app and avoid rate limiting.",
                "warn": None,
                "screenshot_hint": "Reddit API documentation showing user agent format requirements",
            },
        ],
        "api_key_label": "Client ID",
        "api_key_placeholder": "Abc12Def34Ghi56",
        "secret_key_label": "Client Secret",
        "extra_label": 'Extra JSON: {"username":"...","password":"...","subreddit":"...","title":"..."}',
        "extra_placeholder": '{"username": "myreddit", "password": "pass", "subreddit": "test", "title": "My Post"}',
        "doc_url": "https://www.reddit.com/dev/api/",
        "doc_label": "Official Reddit API Docs",
        "errors": [
            {
                "problem": "Invalid credentials — 401 Unauthorized",
                "solution": "Your Reddit username, password, Client ID, or Client Secret is incorrect. Double check each value.",
            },
            {
                "problem": "SUBREDDIT_NOTALLOWED — Cannot post to that subreddit",
                "solution": "Your account doesn't have permission to post in that subreddit (e.g., karma requirement or community restriction). Try 'r/test' first.",
            },
            {
                "problem": "RATELIMIT — Too many requests",
                "solution": "Reddit rate limits new or low-karma accounts. Wait a few minutes and try again.",
            },
            {
                "problem": "403 Forbidden — Account banned or restricted",
                "solution": "Your Reddit account may be shadowbanned or the subreddit has restricted posting. Try posting manually first to confirm.",
            },
        ],
        "video_search": "Reddit API script app Client ID Client Secret automation tutorial 2024",
    },

    # ─────────────────────── INSTAGRAM ────────────────────────
    "instagram": {
        "requirements": [
            "Instagram Business Account",
            "Facebook Page (connected to Instagram)",
            "Meta Developer App",
            "Instagram Graph API enabled",
        ],
        "quick_steps": [
            "Convert Instagram to Business Account",
            "Connect Instagram to Facebook Page",
            "Create Meta Developer App",
            "Enable Instagram Graph API",
            "Generate Page Access Token & paste below",
        ],
        "detailed_steps": [
            {
                "title": "Step 1 — Convert to Instagram Business Account",
                "desc": "Open Instagram app → Go to your <b>Profile</b> → Tap the <b>hamburger menu</b> (≡) → <b>Settings</b> → <b>Account</b> → <b>Switch to Professional Account</b> → Select <b>Business</b>. Follow the steps to connect to a Facebook Page.",
                "link": "https://help.instagram.com/502981923235522",
                "link_label": "Instagram Help: Switch to Business Account",
                "tip": "Personal Instagram accounts cannot use the Graph API to post — Business account is mandatory.",
                "warn": None,
                "screenshot_hint": "Instagram settings showing Switch to Professional Account option",
            },
            {
                "title": "Step 2 — Connect Your Instagram to a Facebook Page",
                "desc": "In Instagram settings go to <b>Account → Linked Accounts → Facebook</b>. Log in to your Facebook account and connect to your Facebook Page. If you don't have a Facebook Page, create one at <a href='https://www.facebook.com/pages/create' target='_blank'>facebook.com/pages/create</a> (it can be a simple business page).",
                "link": "https://www.facebook.com/pages/create",
                "link_label": "Create a Facebook Page",
                "tip": "A personal Facebook profile is NOT the same as a Facebook Page. You need a Page.",
                "warn": "If Instagram and Facebook Page are not linked, the Graph API will not be able to find your account.",
                "screenshot_hint": "Instagram account settings showing Facebook Page linked",
            },
            {
                "title": "Step 3 — Create a Meta Developer App",
                "desc": "Go to <a href='https://developers.facebook.com/' target='_blank'>developers.facebook.com</a> and log in. Click <b>My Apps → Create App</b>. Select app type <b>Business</b>. Fill in app name and contact email. Click <b>Create App</b>.",
                "link": "https://developers.facebook.com/",
                "link_label": "Go to Meta for Developers",
                "tip": None,
                "warn": "Select Business type app — not Consumer or None. This gives access to the Instagram Graph API.",
                "screenshot_hint": "Meta developer console showing Create App form with Business type selected",
            },
            {
                "title": "Step 4 — Add Instagram Graph API Product",
                "desc": "Inside your app dashboard, under <b>Add a Product</b>, find <b>Instagram Graph API</b> and click <b>Set Up</b>. Then go to <b>Instagram Graph API → Getting Started</b> in the left sidebar.",
                "link": None,
                "link_label": None,
                "tip": "You can also add the 'Facebook Login' product which lets you generate access tokens via the Token Debugger.",
                "warn": None,
                "screenshot_hint": "Meta app Products section showing Instagram Graph API being added",
            },
            {
                "title": "Step 5 — Generate a Page Access Token",
                "desc": "Go to the <a href='https://developers.facebook.com/tools/explorer/' target='_blank'>Graph API Explorer</a>. Select your app. Click <b>Generate Access Token</b> and grant required permissions: <code>instagram_basic</code>, <code>instagram_content_publish</code>, <code>pages_show_list</code>, <code>pages_read_engagement</code>. Copy the generated token.",
                "link": "https://developers.facebook.com/tools/explorer/",
                "link_label": "Go to Graph API Explorer",
                "tip": "For a long-lived token (60 days), use the Access Token Debugger to exchange your short-lived token.",
                "warn": "Short-lived tokens expire in 1 hour. Generate a long-lived Page Access Token for uninterrupted posting.",
                "screenshot_hint": "Graph API Explorer showing permission selection and Generate Access Token button",
            },
            {
                "title": "Step 6 — Find Your Instagram Business Account ID",
                "desc": "In the Graph API Explorer, with your access token selected, call: <code>/me/accounts</code>. This shows your Facebook Pages. Copy the Page <code>id</code>. Then call: <code>/{page-id}?fields=instagram_business_account</code> to get your Instagram Business Account ID.",
                "link": "https://developers.facebook.com/tools/explorer/",
                "link_label": "Graph API Explorer",
                "tip": "Your Instagram Business Account ID is different from your Instagram username. It is a long number like 17841400000000000.",
                "warn": None,
                "screenshot_hint": "Graph API Explorer showing /me/accounts response with page ID and instagram_business_account id",
            },
        ],
        "api_key_label": "Page Access Token",
        "api_key_placeholder": "EAABsbCS... (long token starting with EAA)",
        "secret_key_label": None,
        "extra_label": "Instagram Business Account ID",
        "extra_placeholder": "17841400000000000",
        "doc_url": "https://developers.facebook.com/docs/instagram-api/",
        "doc_label": "Official Instagram Graph API Docs",
        "errors": [
            {
                "problem": "(#100) Object does not exist — Wrong Business Account ID",
                "solution": "Your Instagram Business Account ID is incorrect. Use the Graph API Explorer to find it: call <code>/{page-id}?fields=instagram_business_account</code>.",
            },
            {
                "problem": "Token expired — Access token has expired",
                "solution": "Short-lived tokens expire in 1 hour. Generate a <b>long-lived Page Access Token</b> (valid 60 days) using the Token Debugger tool.",
            },
            {
                "problem": "App is in development mode — Cannot access other accounts",
                "solution": "Go to your Meta app dashboard → App Review → Switch app to <b>Live mode</b>.",
            },
            {
                "problem": "Media must be an image — Only images allowed",
                "solution": "Instagram Graph API requires every post to have an image URL. Make sure your post includes a publicly accessible image URL.",
            },
        ],
        "video_search": "Instagram Graph API Page Access Token Business Account ID tutorial Meta developer 2024",
    },

    # ─────────────────────── FACEBOOK ────────────────────────
    "facebook": {
        "requirements": [
            "Facebook Account",
            "Facebook Page (not personal profile)",
            "Meta Developer Account",
            "pages_manage_posts permission",
        ],
        "quick_steps": [
            "Create Meta Developer Account",
            "Create new App (Business type)",
            "Add Pages API product",
            "Generate Page Access Token with permissions",
            "Copy Page ID and paste credentials below",
        ],
        "detailed_steps": [
            {
                "title": "Step 1 — Create a Meta Developer Account",
                "desc": "Go to <a href='https://developers.facebook.com/' target='_blank'>developers.facebook.com</a> and log in with your Facebook account. If you haven't registered as a developer, you'll be prompted to verify your phone number and agree to the developer terms.",
                "link": "https://developers.facebook.com/",
                "link_label": "Go to Meta for Developers",
                "tip": "Use the same Facebook account that administers the Page you want to post to.",
                "warn": None,
                "screenshot_hint": "Meta developer portal login and registration page",
            },
            {
                "title": "Step 2 — Create a New App",
                "desc": "Click <b>My Apps → Create App</b>. Select <b>Business</b> as the app type. Enter your App Name and contact email. Click <b>Create App</b>.",
                "link": None,
                "link_label": None,
                "tip": None,
                "warn": "Select the Business type — other types may not have access to the Pages API.",
                "screenshot_hint": "Meta App creation form with Business type selected and name entered",
            },
            {
                "title": "Step 3 — Add the Pages API Product",
                "desc": "In your app dashboard, scroll down to <b>Add a Product</b>. Find <b>Facebook Login</b> and also <b>Pages API</b>. Click <b>Set Up</b> for Pages API. This allows your app to manage and post to pages.",
                "link": None,
                "link_label": None,
                "tip": "Adding Facebook Login is also helpful — it enables the Token Debugger for easy token generation.",
                "warn": None,
                "screenshot_hint": "Meta app dashboard Products section with Pages API being added",
            },
            {
                "title": "Step 4 — Generate a Page Access Token",
                "desc": "Go to the <a href='https://developers.facebook.com/tools/explorer/' target='_blank'>Graph API Explorer</a>. Select your app. Click <b>Generate Access Token</b>. Grant these permissions:<br>• <code>pages_manage_posts</code><br>• <code>pages_read_engagement</code><br>• <code>pages_show_list</code><br>Select your Facebook Page when prompted. Copy the <b>Page Access Token</b>.",
                "link": "https://developers.facebook.com/tools/explorer/",
                "link_label": "Graph API Explorer",
                "tip": "Use the Access Token Debugger to exchange your short-lived token for a long-lived one (60 days).",
                "warn": "Never use your personal User Access Token to post to pages — always use the Page Access Token.",
                "screenshot_hint": "Graph API Explorer showing Permission selector with pages_manage_posts ticked",
            },
            {
                "title": "Step 5 — Find Your Facebook Page ID",
                "desc": "Option 1: Go to your Facebook Page, click <b>About</b> in the left sidebar. Scroll down to see the <b>Page ID</b> number.<br>Option 2: In Graph API Explorer, call <code>/me/accounts</code> to list your pages and their IDs.",
                "link": None,
                "link_label": None,
                "tip": "Your Page ID is a long number like 123456789012345. It is different from your page's username.",
                "warn": None,
                "screenshot_hint": "Facebook Page About section showing Page ID at the bottom",
            },
            {
                "title": "Step 6 — Submit for App Review (for Live Apps)",
                "desc": "If you want other users to use your app (not just yourself), go to <b>App Review → Permissions and Features</b>. Request access to <code>pages_manage_posts</code> and <code>pages_read_engagement</code>. Provide a screen recording of the use case.",
                "link": "https://developers.facebook.com/docs/app-review",
                "link_label": "Meta App Review Documentation",
                "tip": "For personal use only (just your own page), you don't need App Review approval. Only submit if you're building for other users.",
                "warn": None,
                "screenshot_hint": "Meta App Review page showing permission request form",
            },
        ],
        "api_key_label": "Page Access Token",
        "api_key_placeholder": "EAABsbCS... (long token starting with EAA)",
        "secret_key_label": None,
        "extra_label": "Facebook Page ID",
        "extra_placeholder": "123456789012345",
        "doc_url": "https://developers.facebook.com/docs/pages-api",
        "doc_label": "Official Facebook Pages API Docs",
        "errors": [
            {
                "problem": "OAuthException (190) — Token is invalid or expired",
                "solution": "Your Page Access Token has expired. Go to the Graph API Explorer and generate a fresh token. Use the Token Debugger to get a long-lived token.",
            },
            {
                "problem": "(#200) Requires extended permission: pages_manage_posts",
                "solution": "When generating the access token, make sure to tick the <code>pages_manage_posts</code> permission in the Graph API Explorer.",
            },
            {
                "problem": "App in Development Mode — Only developers can use it",
                "solution": "Switch your app to <b>Live mode</b> in the Meta Dashboard → App Settings → Basic → Status toggle.",
            },
            {
                "problem": "Page not found — Wrong Page ID",
                "solution": "Check your Page ID on your Facebook Page's About section or call <code>/me/accounts</code> in the Graph API Explorer.",
            },
        ],
        "video_search": "Facebook Pages API Page Access Token Graph API Explorer tutorial Meta developer 2024",
    },
}


@router.get("/connect/{platform}", response_class=HTMLResponse)
def connect_page(platform: str, request: Request):
    user_id = get_optional_user_id(request)
    if not user_id:
        return RedirectResponse("/login", status_code=302)

    pinfo = PLATFORMS.get(platform)
    if not pinfo:
        return RedirectResponse("/dashboard", status_code=302)

    instructions = PLATFORM_INSTRUCTIONS.get(platform, {})
    return templates.TemplateResponse("connect_platform.html", {
        "request": request,
        "platform": pinfo,
        "instructions": instructions,
        "user_id": user_id,
    })


@router.post("/api/connect/{platform}")
async def api_connect_platform(
    platform: str,
    request: Request,
    api_key: str = Form(default=""),
    secret_key: str = Form(default=""),
    extra: str = Form(default=""),
    db: Session = Depends(get_db),
):
    user_id = get_optional_user_id(request)
    if not user_id:
        return JSONResponse({"success": False, "message": "Not authenticated"}, status_code=401)

    if platform not in PLATFORMS:
        return JSONResponse({"success": False, "message": "Unknown platform"}, status_code=400)

    # Check if already connected — update or insert
    existing = db.query(UserPlatformKey).filter(
        UserPlatformKey.user_id == user_id,
        UserPlatformKey.platform_name == platform,
    ).first()

    encrypted_api = encrypt_value(api_key) if api_key else ""
    encrypted_secret = encrypt_value(secret_key) if secret_key else ""
    encrypted_extra = encrypt_value(extra) if extra else ""

    if existing:
        existing.encrypted_api_key = encrypted_api
        existing.encrypted_secret_key = encrypted_secret
        existing.encrypted_extra = encrypted_extra
    else:
        new_key = UserPlatformKey(
            user_id=user_id,
            platform_name=platform,
            encrypted_api_key=encrypted_api,
            encrypted_secret_key=encrypted_secret,
            encrypted_extra=encrypted_extra,
        )
        db.add(new_key)

    db.commit()
    return JSONResponse({"success": True, "message": f"{PLATFORMS[platform]['display_name']} connected successfully!"})


@router.delete("/api/disconnect/{platform}")
async def api_disconnect_platform(
    platform: str,
    request: Request,
    db: Session = Depends(get_db),
):
    user_id = get_optional_user_id(request)
    if not user_id:
        return JSONResponse({"success": False, "message": "Not authenticated"}, status_code=401)

    db.query(UserPlatformKey).filter(
        UserPlatformKey.user_id == user_id,
        UserPlatformKey.platform_name == platform,
    ).delete()
    db.commit()

    return JSONResponse({"success": True, "message": f"Disconnected from {platform}"})
