#!/usr/bin/env python3
"""
LinkedIn Auto-Poster via Safari (macOS)
Automatiza posts no LinkedIn usando Safari e AppleScript

Requisitos:
- macOS
- Safari com login no LinkedIn
- Permissões de Acessibilidade habilitadas para Terminal/Python

Uso:
    python3 linkedin-post.py "Seu post aqui"
    python3 linkedin-post.py "Seu post" -n  # Não posta automaticamente
"""

import subprocess
import time
import sys
import argparse


def run_applescript(script: str) -> str:
    """Executa AppleScript e retorna o resultado."""
    result = subprocess.run(
        ["osascript", "-e", script],
        capture_output=True,
        text=True
    )
    if result.returncode != 0:
        raise Exception(f"AppleScript error: {result.stderr}")
    return result.stdout.strip()


def open_linkedin_feed():
    """Abre o Safari no LinkedIn feed."""
    script = '''
    tell application "Safari"
        activate

        if (count of windows) = 0 then
            make new document
        end if

        set URL of front document to "https://www.linkedin.com/feed/"
    end tell
    '''
    run_applescript(script)
    print("✓ Safari aberto no LinkedIn")


def wait_for_page_load(timeout: int = 15):
    """Aguarda a página carregar."""
    print("⏳ Aguardando página carregar...", end="", flush=True)

    for i in range(timeout):
        time.sleep(1)
        print(".", end="", flush=True)

        script = '''
        tell application "Safari"
            set pageState to do JavaScript "document.readyState" in front document
            return pageState
        end tell
        '''
        try:
            state = run_applescript(script)
            if state == "complete":
                print(" ✓")
                return True
        except:
            pass

    print(" (timeout)")
    return False


def click_start_post():
    """Clica no botão 'Start a post' para abrir o modal."""
    script = '''
    tell application "Safari"
        activate
        delay 0.5

        set js to "
            (function() {
                // Procura pelo texto do botão (PT-BR ou EN)
                var buttons = document.querySelectorAll('button');
                for (var b of buttons) {
                    var text = b.textContent.toLowerCase();
                    if (text.includes('comece uma publica') ||
                        text.includes('start a post') ||
                        text.includes('começar publica')) {
                        b.click();
                        return 'clicked';
                    }
                }

                // Fallback: botão com classe artdeco na área de share
                var shareBtn = document.querySelector('.share-box-feed-entry__trigger');
                if (shareBtn) {
                    shareBtn.click();
                    return 'clicked';
                }

                return 'not_found';
            })()
        "

        set result to do JavaScript js in front document
        return result
    end tell
    '''

    result = run_applescript(script)

    if result == "clicked":
        print("✓ Modal de post aberto")
        return True
    else:
        print("⚠ Botão não encontrado, tentando clicar na área de post...")
        # Clica na área de "Start a post" via coordenadas aproximadas
        click_script = '''
        tell application "Safari"
            activate
            delay 0.3
            set js to "
                (function() {
                    var shareArea = document.querySelector('.share-box-feed-entry__closed-share-box');
                    if (shareArea) {
                        shareArea.click();
                        return 'clicked';
                    }
                    return 'not_found';
                })()
            "
            set result to do JavaScript js in front document
            return result
        end tell
        '''
        run_applescript(click_script)
        return True


def wait_for_modal(timeout: int = 8):
    """Aguarda o modal de post abrir."""
    print("⏳ Aguardando modal...", end="", flush=True)

    for i in range(timeout):
        time.sleep(1)
        print(".", end="", flush=True)

        script = '''
        tell application "Safari"
            set js to "
                (function() {
                    var editor = document.querySelector('.ql-editor');
                    return editor ? 'found' : 'not_found';
                })()
            "
            set result to do JavaScript js in front document
            return result
        end tell
        '''
        try:
            result = run_applescript(script)
            if result == "found":
                print(" ✓")
                return True
        except:
            pass

    print(" (timeout)")
    return False


def type_post(text: str):
    """Digita o texto do post via JavaScript (sem keystroke)."""
    # Escapa o texto para JavaScript
    escaped = text.replace("\\", "\\\\").replace("'", "\\'").replace('"', '\\"').replace("\n", "\\n").replace("\r", "")

    # Monta o JavaScript
    js = f"(function(){{var e=document.querySelector('.ql-editor');if(!e)return'nf';e.focus();e.click();document.execCommand('insertText',false,'{escaped}');return'ok'}})()"

    # Salva JS em arquivo temporário com encoding UTF-8
    import tempfile
    with tempfile.NamedTemporaryFile(mode='w', suffix='.js', delete=False, encoding='utf-8') as f:
        f.write(js)
        js_file = f.name

    script = f'''
    tell application "Safari"
        activate
        delay 0.5
        set jsCode to read POSIX file "{js_file}" as «class utf8»
        do JavaScript jsCode in front document
    end tell
    '''

    try:
        result = run_applescript(script)
        import os
        os.unlink(js_file)

        if "ok" in str(result) or result == "ok" or result == "":
            time.sleep(0.3)
            suffix = "..." if len(text) > 50 else ""
            print(f"✓ Post digitado: {text[:50]}{suffix}")
            return True
        elif "nf" in str(result):
            print("⚠ Editor não encontrado")
            return False
        else:
            # Assume sucesso se não houver erro claro
            time.sleep(0.3)
            suffix = "..." if len(text) > 50 else ""
            print(f"✓ Post digitado: {text[:50]}{suffix}")
            return True
    except Exception as e:
        print(f"⚠ Erro: {e}")
        return False


def click_post_button():
    """Clica no botão de postar."""
    script = '''
    tell application "Safari"
        activate
        delay 0.5

        set js to "
            (function() {
                // Botão 'Post' no modal do LinkedIn
                var btn = document.querySelector('button.share-actions__primary-action');
                if (!btn) {
                    btn = document.querySelector('[data-control-name=\\"share.post\\"]');
                }
                if (!btn) {
                    // Tenta pelo texto
                    var buttons = document.querySelectorAll('button');
                    for (var b of buttons) {
                        var text = b.textContent.trim().toLowerCase();
                        if (text === 'post' || text === 'publicar' || text === 'postar') {
                            if (!b.disabled) {
                                btn = b;
                                break;
                            }
                        }
                    }
                }
                if (btn && !btn.disabled) {
                    btn.click();
                    return 'clicked';
                }
                return 'not_found';
            })()
        "

        set result to do JavaScript js in front document
        return result
    end tell
    '''

    result = run_applescript(script)

    if result == "clicked":
        print("✓ Botão Post clicado!")
        return True
    else:
        print("⚠ Botão Post não encontrado, tentando via Cmd+Enter...")
        shortcut_script = '''
        tell application "System Events"
            tell process "Safari"
                keystroke return using command down
            end tell
        end tell
        '''
        run_applescript(shortcut_script)
        print("✓ Tentou postar via Cmd+Enter")
        return True


def check_accessibility_permissions():
    """Verifica se as permissões de acessibilidade estão habilitadas."""
    script = '''
    tell application "System Events"
        set frontApp to name of first application process whose frontmost is true
        return frontApp
    end tell
    '''
    try:
        run_applescript(script)
        return True
    except:
        return False


def post_linkedin(text: str, auto_post: bool = True):
    """
    Fluxo completo para postar no LinkedIn.

    Args:
        text: O texto do post (sem limite rígido como Twitter)
        auto_post: Se True, clica automaticamente no botão Post
    """
    # Verifica permissões
    if not check_accessibility_permissions():
        print("❌ Permissões de Acessibilidade necessárias!")
        print("   Vá em: Preferências do Sistema > Privacidade > Acessibilidade")
        print("   Adicione Terminal ou a aplicação Python")
        return False

    print(f"\n💼 Postando no LinkedIn ({len(text)} caracteres)")
    print("-" * 50)

    # 1. Abre LinkedIn feed
    open_linkedin_feed()

    # 2. Aguarda carregar
    if not wait_for_page_load(15):
        print("❌ Página não carregou a tempo")
        return False

    # 3. Aguarda mais um pouco
    time.sleep(2)

    # 4. Clica em "Start a post"
    click_start_post()

    # 5. Aguarda modal abrir
    if not wait_for_modal(5):
        print("⚠ Modal pode não ter aberto corretamente")
        time.sleep(2)

    # 6. Digita o post
    time.sleep(1)
    if not type_post(text):
        print("❌ Falha ao digitar post")
        return False

    # 7. Posta (se auto_post ativado)
    if auto_post:
        time.sleep(1)
        click_post_button()
        print("\n✅ Post enviado!")
    else:
        print("\n⏸ Post preparado. Revise e clique em Post manualmente.")
        print("  (Remova -n para postar automaticamente)")

    return True


def main():
    parser = argparse.ArgumentParser(
        description="Automatiza posts no LinkedIn via Safari",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Exemplos:
  python3 linkedin-post.py "Meu post no LinkedIn!"
  python3 linkedin-post.py "Post longo..." -n    # Apenas prepara

Notas:
  - Requer login no LinkedIn via Safari
  - Habilite Acessibilidade em Preferências do Sistema
  - Por padrão, posta automaticamente. Use -n para revisar antes.
        """
    )

    parser.add_argument(
        "post",
        nargs="?",
        help="Texto do post"
    )

    parser.add_argument(
        "--no-post", "-n",
        action="store_true",
        help="NÃO posta automaticamente (apenas prepara)"
    )

    args = parser.parse_args()

    if args.post:
        post_linkedin(args.post, auto_post=not args.no_post)
    else:
        parser.print_help()


if __name__ == "__main__":
    main()
