from flask import Flask, request
import requests
import base64
import json

app = Flask(__name__)

# 🔐 PUT YOUR REAL VALUES HERE
CLIENT_ID = "86yocrmmmquhw0"
CLIENT_SECRET = "WPL_AP1.5RIxj10fbJavxZgB.DN9PQA=="
REDIRECT_URI = "http://localhost:5000/callback"

access_token_global = None
author_urn_global = None


@app.route("/")
def home():
    auth_url = (
        "https://www.linkedin.com/oauth/v2/authorization"
        "?response_type=code"
        f"&client_id={CLIENT_ID}"
        f"&redirect_uri={REDIRECT_URI}"
        "&scope=openid%20profile%20w_member_social"
    )

    return f"""
    <!DOCTYPE html>
    <html>
    <head>
        <title>LinkedIn Automation</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body class="bg-dark text-white d-flex align-items-center justify-content-center vh-100">

        <div class="text-center">
            <h1 class="mb-4">🚀 LinkedIn Automation System</h1>
            <p class="mb-4">Post directly to your LinkedIn with rich UI</p>
            <a href="{auth_url}" class="btn btn-success btn-lg px-4">
                🔐 Login with LinkedIn
            </a>
        </div>

    </body>
    </html>
    """


@app.route("/callback")
def callback():
    global access_token_global, author_urn_global

    code = request.args.get("code")

    token_response = requests.post(
        "https://www.linkedin.com/oauth/v2/accessToken",
        data={
            "grant_type": "authorization_code",
            "code": code,
            "client_id": CLIENT_ID,
            "client_secret": CLIENT_SECRET,
            "redirect_uri": REDIRECT_URI
        }
    )

    token_json = token_response.json()
    access_token = token_json.get("access_token")
    id_token = token_json.get("id_token")

    if not access_token:
        return f"Token Error: {token_json}"

    access_token_global = access_token

    # Decode id_token
    payload = id_token.split('.')[1]
    padded = payload + '=' * (-len(payload) % 4)
    decoded = base64.urlsafe_b64decode(padded)
    user_info = json.loads(decoded)

    user_id = user_info["sub"]
    author_urn_global = f"urn:li:person:{user_id}"

    return """
    <!DOCTYPE html>
    <html>
    <head>
        <title>Create LinkedIn Post</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body class="bg-light">

        <div class="container mt-5">
            <div class="card shadow-lg p-4">
                <h2 class="text-center mb-4">✍ Create LinkedIn Post</h2>

                <form action="/post" method="post" enctype="multipart/form-data">
                    
                    <div class="mb-3">
                        <label class="form-label">Post Content</label>
                        <textarea name="text" class="form-control" rows="4" placeholder="Write something amazing..." required></textarea>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Upload Image (Optional)</label>
                        <input type="file" name="image" class="form-control">
                    </div>

                    <div class="d-grid">
                        <button type="submit" class="btn btn-primary btn-lg">
                            📤 Publish to LinkedIn
                        </button>
                    </div>

                </form>
            </div>
        </div>

    </body>
    </html>
    """


@app.route("/post", methods=["POST"])
def create_post():
    global access_token_global, author_urn_global

    text = request.form.get("text")
    image = request.files.get("image")

    headers = {
        "Authorization": f"Bearer {access_token_global}",
        "X-Restli-Protocol-Version": "2.0.0"
    }

    if image and image.filename != "":

        # Register image upload
        register_upload = requests.post(
            "https://api.linkedin.com/v2/assets?action=registerUpload",
            headers={**headers, "Content-Type": "application/json"},
            json={
                "registerUploadRequest": {
                    "recipes": ["urn:li:digitalmediaRecipe:feedshare-image"],
                    "owner": author_urn_global,
                    "serviceRelationships": [
                        {
                            "relationshipType": "OWNER",
                            "identifier": "urn:li:userGeneratedContent"
                        }
                    ]
                }
            }
        )

        upload_data = register_upload.json()
        upload_url = upload_data["value"]["uploadMechanism"] \
            ["com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest"]["uploadUrl"]
        asset = upload_data["value"]["asset"]

        # Upload image binary
        requests.put(upload_url, data=image.read())

        # Create post with image
        post_response = requests.post(
            "https://api.linkedin.com/v2/ugcPosts",
            headers={**headers, "Content-Type": "application/json"},
            json={
                "author": author_urn_global,
                "lifecycleState": "PUBLISHED",
                "specificContent": {
                    "com.linkedin.ugc.ShareContent": {
                        "shareCommentary": {"text": text},
                        "shareMediaCategory": "IMAGE",
                        "media": [
                            {
                                "status": "READY",
                                "description": {"text": text},
                                "media": asset,
                                "title": {"text": "Uploaded Image"}
                            }
                        ]
                    }
                },
                "visibility": {
                    "com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"
                }
            }
        )

    else:
        # Text only post
        post_response = requests.post(
            "https://api.linkedin.com/v2/ugcPosts",
            headers={**headers, "Content-Type": "application/json"},
            json={
                "author": author_urn_global,
                "lifecycleState": "PUBLISHED",
                "specificContent": {
                    "com.linkedin.ugc.ShareContent": {
                        "shareCommentary": {"text": text},
                        "shareMediaCategory": "NONE"
                    }
                },
                "visibility": {
                    "com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"
                }
            }
        )

    return """
    <!DOCTYPE html>
    <html>
    <head>
        <title>Success</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body class="bg-light d-flex align-items-center justify-content-center vh-100">

        <div class="card p-5 shadow-lg text-center">
            <h2 class="text-success mb-3">✅ Post Published Successfully!</h2>
            <p>Your LinkedIn post has been published.</p>
            <a href="/" class="btn btn-primary mt-3">Create Another Post</a>
        </div>

    </body>
    </html>
    """


if __name__ == "__main__":
    app.run(port=5000)
