"""
LinkedIn OAuth2 Router
Ports the full OAuth2 flow from linkdintest/app.py into the main FastAPI platform.
Flow:
  1. GET /linkedin/login  → Redirect user to LinkedIn authorization URL
  2. GET /linkedin/callback → Exchange auth code for access token, save to DB
"""
import base64
import json
import httpx
from fastapi import APIRouter, Request, Depends
from fastapi.responses import RedirectResponse, HTMLResponse
from sqlalchemy.orm import Session

from app.config import settings
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

router = APIRouter(prefix="/linkedin", tags=["LinkedIn OAuth"])

LINKEDIN_AUTH_URL = "https://www.linkedin.com/oauth/v2/authorization"
LINKEDIN_TOKEN_URL = "https://www.linkedin.com/oauth/v2/accessToken"


@router.get("/login")
def linkedin_login(request: Request):
    """Redirect the user to LinkedIn's OAuth2 authorization page."""
    user_id = get_optional_user_id(request)
    if not user_id:
        return RedirectResponse("/login", status_code=302)

    auth_url = (
        f"{LINKEDIN_AUTH_URL}"
        f"?response_type=code"
        f"&client_id={settings.LINKEDIN_CLIENT_ID}"
        f"&redirect_uri={settings.LINKEDIN_REDIRECT_URI}"
        f"&scope=openid%20profile%20w_member_social"
    )
    return RedirectResponse(auth_url, status_code=302)


@router.get("/callback", response_class=HTMLResponse)
async def linkedin_callback(request: Request, db: Session = Depends(get_db)):
    """Handle LinkedIn callback: exchange code for token and save to DB."""
    user_id = get_optional_user_id(request)
    if not user_id:
        return RedirectResponse("/login", status_code=302)

    code = request.query_params.get("code")
    error = request.query_params.get("error")

    if error or not code:
        return _result_page(
            success=False,
            message=f"LinkedIn authorization failed: {error or 'No code received'}"
        )

    # Exchange code for access token
    try:
        async with httpx.AsyncClient(timeout=15) as client:
            token_resp = await client.post(
                LINKEDIN_TOKEN_URL,
                data={
                    "grant_type": "authorization_code",
                    "code": code,
                    "client_id": settings.LINKEDIN_CLIENT_ID,
                    "client_secret": settings.LINKEDIN_CLIENT_SECRET,
                    "redirect_uri": settings.LINKEDIN_REDIRECT_URI,
                },
                headers={"Content-Type": "application/x-www-form-urlencoded"},
            )
    except Exception as e:
        return _result_page(success=False, message=f"Token exchange failed: {str(e)}")

    token_json = token_resp.json()
    access_token = token_json.get("access_token")
    id_token = token_json.get("id_token")

    if not access_token:
        return _result_page(success=False, message=f"No access token received: {token_json}")

    # Decode id_token to get LinkedIn person URN (sub field)
    person_urn = ""
    if id_token:
        try:
            payload = id_token.split(".")[1]
            padded = payload + "=" * (-len(payload) % 4)
            decoded = base64.urlsafe_b64decode(padded)
            user_info = json.loads(decoded)
            sub = user_info.get("sub", "")
            if sub:
                person_urn = f"urn:li:person:{sub}"
        except Exception:
            pass  # URN is optional; service will fetch it via /v2/me

    # Save / update encrypted credentials in DB
    existing = db.query(UserPlatformKey).filter(
        UserPlatformKey.user_id == user_id,
        UserPlatformKey.platform_name == "linkedin",
    ).first()

    enc_token = encrypt_value(access_token)
    enc_urn = encrypt_value(person_urn) if person_urn else ""

    if existing:
        existing.encrypted_api_key = enc_token
        existing.encrypted_extra = enc_urn
    else:
        db.add(UserPlatformKey(
            user_id=user_id,
            platform_name="linkedin",
            encrypted_api_key=enc_token,
            encrypted_secret_key="",
            encrypted_extra=enc_urn,
        ))

    db.commit()

    return _result_page(
        success=True,
        message="✅ LinkedIn connected successfully! Your access token has been saved."
    )


def _result_page(success: bool, message: str) -> HTMLResponse:
    """Returns a simple inline HTML result page after OAuth callback."""
    icon = "✅" if success else "❌"
    color = "#28a745" if success else "#dc3545"
    return HTMLResponse(f"""
    <!DOCTYPE html>
    <html>
    <head>
      <title>LinkedIn Connection</title>
      <meta charset="utf-8">
      <style>
        body {{ font-family: 'Segoe UI', sans-serif; background: #0d1117;
               color: #c9d1d9; display: flex; align-items: center;
               justify-content: center; height: 100vh; margin: 0; }}
        .card {{ background: #161b22; border: 1px solid #30363d;
                 border-radius: 16px; padding: 40px 50px; text-align: center;
                 max-width: 500px; box-shadow: 0 8px 32px rgba(0,0,0,0.5); }}
        h2 {{ color: {color}; font-size: 1.8rem; margin-bottom: 10px; }}
        p  {{ color: #8b949e; margin-bottom: 24px; }}
        a  {{ background: #0077b5; color: white; text-decoration: none;
               padding: 12px 28px; border-radius: 8px; font-weight: 600; }}
        a:hover {{ background: #005582; }}
      </style>
    </head>
    <body>
      <div class="card">
        <h2>{icon} {'Success' if success else 'Failed'}</h2>
        <p>{message}</p>
        <a href="/dashboard">← Back to Dashboard</a>
      </div>
    </body>
    </html>
    """)
