#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ================================================== #
# This file is a part of PYGPT package               #
# Website: https://pygpt.net                         #
# GitHub:  https://github.com/szczyglis-dev/py-gpt   #
# MIT License                                        #
# Created By  : Marcin Szczygliński                  #
# Updated Date: 2025.08.14 00:00:00                  #
# ================================================== #

from pygpt_net.plugin.base.config import BaseConfig, BasePlugin


class Config(BaseConfig):
    def __init__(self, plugin: BasePlugin = None, *args, **kwargs):
        super(Config, self).__init__(plugin)
        self.plugin = plugin

    def from_defaults(self, plugin: BasePlugin = None):
        # Endpoints / HTTP
        plugin.add_option(
            "graph_version",
            type="text",
            value="v21.0",
            label="Graph API version",
            description="API version (e.g. v21.0).",
        )
        plugin.add_option(
            "api_base",
            type="text",
            value="https://graph.facebook.com",
            label="API base",
            description="Base API host (Graph API). Version is appended automatically.",
        )
        plugin.add_option(
            "authorize_base",
            type="text",
            value="https://www.facebook.com",
            label="Authorize base",
            description="Base for OAuth authorize (Login dialog). Version is appended automatically.",
        )
        plugin.add_option(
            "http_timeout",
            type="int",
            value=30,
            label="HTTP timeout (s)",
            description="Requests timeout in seconds.",
        )

        # OAuth2 (PKCE)
        plugin.add_option(
            "oauth2_client_id",
            type="text",
            value="",
            label="App ID (client_id)",
            description="Facebook App ID.",
            secret=False,
        )
        plugin.add_option(
            "oauth2_client_secret",
            type="text",
            value="",
            label="App Secret (optional)",
            description="Needed for long-lived token exchange and if not using PKCE.",
            secret=True,
        )
        plugin.add_option(
            "oauth2_confidential",
            type="bool",
            value=False,
            label="Confidential client (use client_secret on exchange)",
            description="If enabled, code exchange includes client_secret instead of code_verifier.",
        )
        plugin.add_option(
            "oauth2_redirect_uri",
            type="text",
            value="http://127.0.0.1:8732/callback",
            label="Redirect URI",
            description="Must exactly match one of the Valid OAuth Redirect URIs in your Meta App.",
        )
        plugin.add_option(
            "oauth2_scopes",
            type="text",
            value="public_profile pages_show_list pages_read_engagement pages_manage_posts pages_read_user_content openid",
            label="Scopes",
            description="Space-separated permissions for Authorization Code (PKCE).",
        )
        plugin.add_option(
            "oauth2_code_verifier",
            type="text",
            value="",
            label="(auto) code_verifier",
            description="Generated by fb_oauth_begin.",
            secret=True,
        )
        plugin.add_option(
            "oauth2_state",
            type="text",
            value="",
            label="(auto) state",
            description="Generated by fb_oauth_begin.",
            secret=True,
        )
        plugin.add_option(
            "oauth2_nonce",
            type="text",
            value="",
            label="(auto) nonce",
            description="Generated by fb_oauth_begin (OIDC).",
            secret=True,
        )
        plugin.add_option(
            "oauth2_access_token",
            type="textarea",
            value="",
            label="(auto) User access token",
            description="Stored user access token.",
            secret=True,
        )
        plugin.add_option(
            "oauth2_expires_at",
            type="text",
            value="0",
            label="(auto) Expires at (unix)",
            description="Auto-calculated expiry time.",
            secret=False,
        )

        # Convenience cache
        plugin.add_option(
            "user_id",
            type="text",
            value="",
            label="(auto) User ID",
            description="Cached after fb_me or oauth exchange.",
        )
        plugin.add_option(
            "user_name",
            type="text",
            value="",
            label="(auto) User name",
            description="Cached after fb_me or oauth exchange.",
        )
        plugin.add_option(
            "fb_page_id",
            type="text",
            value="",
            label="(auto) Default Page ID",
            description="Chosen by fb_page_set_default.",
        )
        plugin.add_option(
            "fb_page_name",
            type="text",
            value="",
            label="(auto) Default Page name",
            description="Chosen by fb_page_set_default.",
        )
        plugin.add_option(
            "fb_page_access_token",
            type="textarea",
            value="",
            label="(auto) Default Page access token",
            description="Cached via fb_page_set_default or on demand.",
            secret=True,
        )

        # OAuth UX
        plugin.add_option(
            "oauth_auto_begin",
            type="bool",
            value=True,
            label="Auto-start OAuth when required",
            description="If a command needs user token, begin PKCE flow automatically.",
        )
        plugin.add_option(
            "oauth_open_browser",
            type="bool",
            value=True,
            label="Open browser automatically",
            description="Open authorize URL in default browser.",
        )
        plugin.add_option(
            "oauth_local_server",
            type="bool",
            value=True,
            label="Use local server for OAuth",
            description="Start local HTTP server to capture redirect.",
        )
        plugin.add_option(
            "oauth_local_timeout",
            type="int",
            value=180,
            label="OAuth local timeout (s)",
            description="How long to wait for redirect with code.",
        )
        plugin.add_option(
            "oauth_success_html",
            type="textarea",
            value="<html><body><h3>Authorization complete. You can close this window.</h3></body></html>",
            label="Success HTML",
            description="HTML shown on local callback success.",
        )
        plugin.add_option(
            "oauth_fail_html",
            type="textarea",
            value="<html><body><h3>Authorization failed.</h3></body></html>",
            label="Fail HTML",
            description="HTML shown on local callback error.",
        )
        plugin.add_option(
            "oauth_local_port",
            type="int",
            value=8732,
            label="OAuth local port (0=auto)",
            description="Local HTTP port for callback; use >1024. Must be allowed in App.",
        )
        plugin.add_option(
            "oauth_allow_port_fallback",
            type="bool",
            value=True,
            label="Allow fallback port if busy",
            description="If preferred port is busy/forbidden, pick a free local port.",
        )

        # ---------------- Commands ----------------

        # Auth
        plugin.add_cmd(
            "fb_oauth_begin",
            instruction="Begin OAuth2 (PKCE) flow (returns authorize URL).",
            params=[
                {"name": "scopes", "type": "str", "required": False, "description": "Override permissions (space-separated)"},
                {"name": "state", "type": "str", "required": False, "description": "Optional CSRF state"},
            ],
            enabled=True,
            description="Auth: begin OAuth2",
            tab="auth",
        )
        plugin.add_cmd(
            "fb_oauth_exchange",
            instruction="Exchange authorization code for user access token.",
            params=[
                {"name": "code", "type": "str", "required": True, "description": "Authorization code"},
                {"name": "state", "type": "str", "required": False, "description": "State (if used)"},
            ],
            enabled=True,
            description="Auth: exchange code",
            tab="auth",
        )
        plugin.add_cmd(
            "fb_token_extend",
            instruction="Exchange short-lived user token for long-lived token (requires app secret).",
            params=[],
            enabled=True,
            description="Auth: extend user token",
            tab="auth",
        )

        # Me
        plugin.add_cmd(
            "fb_me",
            instruction="Get authorized user profile.",
            params=[
                {"name": "fields", "type": "str", "required": False, "description": "Default: id,name"},
            ],
            enabled=True,
            description="Users: me",
            tab="users",
        )

        # Pages
        plugin.add_cmd(
            "fb_pages_list",
            instruction="List Pages I manage (id,name,access_token,tasks).",
            params=[
                {"name": "fields", "type": "str", "required": False, "description": "Default: id,name,access_token,tasks"},
                {"name": "limit", "type": "int", "required": False, "description": "Default 25"},
                {"name": "after", "type": "str", "required": False, "description": "Paging cursor"},
                {"name": "before", "type": "str", "required": False, "description": "Paging cursor"},
            ],
            enabled=True,
            description="Pages: list",
            tab="pages",
        )
        plugin.add_cmd(
            "fb_page_set_default",
            instruction="Set default Page (caches name and access token).",
            params=[
                {"name": "page_id", "type": "str", "required": True, "description": "Page ID"},
                {"name": "fetch_token", "type": "bool", "required": False, "description": "Fetch and cache page access token"},
            ],
            enabled=True,
            description="Pages: set default",
            tab="pages",
        )

        # Posts
        plugin.add_cmd(
            "fb_page_posts",
            instruction="Get Page feed (posts).",
            params=[
                {"name": "page_id", "type": "str", "required": False, "description": "Defaults to selected page"},
                {"name": "fields", "type": "str", "required": False, "description": "Default: id,message,created_time,permalink_url,is_published"},
                {"name": "limit", "type": "int", "required": False, "description": "Default 25"},
                {"name": "since", "type": "str", "required": False, "description": "Unix or ISO8601"},
                {"name": "until", "type": "str", "required": False, "description": "Unix or ISO8601"},
                {"name": "after", "type": "str", "required": False, "description": "Paging cursor"},
                {"name": "before", "type": "str", "required": False, "description": "Paging cursor"},
            ],
            enabled=True,
            description="Posts: list",
            tab="posts",
        )
        plugin.add_cmd(
            "fb_page_post_create",
            instruction="Publish a Page post (text/link and optional photos).",
            params=[
                {"name": "page_id", "type": "str", "required": False, "description": "Defaults to selected page"},
                {"name": "message", "type": "str", "required": False, "description": "Post text"},
                {"name": "link", "type": "str", "required": False, "description": "URL link"},
                {"name": "published", "type": "bool", "required": False, "description": "Default true"},
                {"name": "scheduled_publish_time", "type": "str", "required": False, "description": "Unix seconds or ISO8601 (requires published=false)"},
                {"name": "media_fbids", "type": "list", "required": False, "description": "Photo IDs uploaded earlier"},
                {"name": "photo_urls", "type": "list", "required": False, "description": "Auto-upload URLs (unpublished then attach)"},
                {"name": "photo_paths", "type": "list", "required": False, "description": "Auto-upload local files (unpublished then attach)"},
                {"name": "targeting", "type": "dict", "required": False, "description": "Audience targeting object"},
            ],
            enabled=True,
            description="Posts: create",
            tab="posts",
        )
        plugin.add_cmd(
            "fb_page_post_delete",
            instruction="Delete a Page post.",
            params=[
                {"name": "post_id", "type": "str", "required": True, "description": "Page post ID (e.g. {pageid}_{postid})"},
            ],
            enabled=True,
            description="Posts: delete",
            tab="posts",
        )

        # Media
        plugin.add_cmd(
            "fb_page_photo_upload",
            instruction="Upload a photo to Page (local path or URL).",
            params=[
                {"name": "page_id", "type": "str", "required": False, "description": "Defaults to selected page"},
                {"name": "path", "type": "str", "required": False, "description": "Local file path"},
                {"name": "url", "type": "str", "required": False, "description": "Remote image URL"},
                {"name": "caption", "type": "str", "required": False, "description": "Photo caption"},
                {"name": "published", "type": "bool", "required": False, "description": "Default true"},
                {"name": "temporary", "type": "bool", "required": False, "description": "Required for scheduled multi-photo"},
            ],
            enabled=True,
            description="Media: upload photo",
            tab="media",
        )