import os
import httpx
from dotenv import load_dotenv
from database import SessionLocal
from models.auth_user_modal import User

load_dotenv()

CLIENT_ID = os.getenv("LINKEDIN_CLIENT_ID")
CLIENT_SECRET = os.getenv("LINKEDIN_CLIENT_SECRET")
REDIRECT_URI = os.getenv("LINKEDIN_REDIRECT_URI")


async def get_linkedin_user(code: str):
    try:
        # 1. Get access token
        async with httpx.AsyncClient() as client:
            token_response = await client.post(
                url="https://www.linkedin.com/oauth/v2/accessToken",
                data={
                    "grant_type": "authorization_code",
                    "code": code,
                    "redirect_uri": REDIRECT_URI,
                    "client_id": CLIENT_ID,
                    "client_secret": CLIENT_SECRET
                },
                headers={"Content-Type": "application/x-www-form-urlencoded"}
            )
            token_response.raise_for_status()
            token_data = token_response.json()
            access_token = token_data["access_token"]

            # 2. Get profile info
            profile_response = await client.get(
                "https://api.linkedin.com/v2/me",
                headers={"Authorization": f"Bearer {access_token}"}
            )
            profile_response.raise_for_status()
            profile = profile_response.json()

            # 3. Get email
            email_response = await client.get(
                "https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))",
                headers={"Authorization": f"Bearer {access_token}"}
            )
            email_response.raise_for_status()
            email_data = email_response.json()

            user_data = {
                "id": profile["id"],
                "name": f"{profile.get('localizedFirstName', '')} {profile.get('localizedLastName', '')}",
                "email": email_data["elements"][0]["handle~"]["emailAddress"],
                "picture": "",  # LinkedIn requires a separate request for picture (optional)
            }

            # Store in DB
            db = SessionLocal()
            try:
                existing = db.query(User).filter(User.google_id == user_data["id"]).first()
                if not existing:
                    user = User(
                        google_id=user_data["id"],
                        name=user_data["name"],
                        email=user_data["email"],
                        picture=user_data["picture"],
                    )
                    db.add(user)
                    db.commit()
                    db.refresh(user)
                    print("✅ LinkedIn user stored:", user.email)
                else:
                    print("ℹ️ LinkedIn user already exists:", existing.email)
            finally:
                db.close()

            return user_data

    except httpx.HTTPStatusError as e:
        print("❌ LinkedIn login failed:", e.response.text)
        return {"error": "LinkedIn OAuth failed", "details": e.response.text}
