import requests
import json
import os
import time

def save_session(session_id):
    # Create file if it doesn't exist
    if not os.path.exists('sessions.txt'):
        with open('sessions.txt', 'w') as f:
            f.write('')  # Create empty file
    
    # Read existing sessions
    with open('sessions.txt', 'r') as f:
        existing_sessions = f.read().splitlines()
    
    # Check for duplicate sessions
    if session_id not in existing_sessions:
        with open('sessions.txt', 'a') as f:
            # Add new session with newline if file isn't empty
            if os.path.getsize('sessions.txt') > 0:
                f.write('\n')
            f.write(session_id)
        print(f"\n[✓] New session saved successfully")
    else:
        print(f"\n[!] This session already exists")

def get_instagram_session():
    # --- Account credentials ---
    username = input("Enter your Instagram username: ")
    password = input("Enter your Instagram password: ")

    # --- Login URL ---
    login_url = "https://www.instagram.com/api/v1/web/accounts/login/ajax/"

    # --- Create session and set headers ---
    session = requests.Session()
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
        "X-Requested-With": "XMLHttpRequest",
        "Referer": "https://www.instagram.com/accounts/login/",
        "x-csrftoken": "missing",
    }

    try:
        # --- Get CSRF Token first ---
        session.get("https://www.instagram.com/accounts/login/", headers=headers)
        csrf_token = session.cookies.get("csrftoken")
        
        if not csrf_token:
            print("[!] Failed to get CSRF Token")
            return

        headers["x-csrftoken"] = csrf_token

        # --- Send login data ---
        login_data = {
            "username": username,
            "enc_password": f"#PWD_INSTAGRAM_BROWSER:0:{int(time.time())}:{password}",
        }

        response = session.post(login_url, data=login_data, headers=headers)
        response_data = response.json()

        # --- Check login success ---
        if response_data.get("authenticated"):
            session_id = session.cookies.get("sessionid")
            print("\n[✓] Login successful!")
            print(f"[✓] Session ID: {session_id[:20]}...")  # Show partial session for security
            
            # Save session to file
            save_session(session_id)
            return session_id
        else:
            print("\n[!] Login failed. Reason:", response_data.get("message", "Unknown"))
            return None
            
    except Exception as e:
        print(f"\n[!] Error occurred: {str(e)}")
        return None

def main():
    print("\nInstagram Session Extractor")
    print("--------------------------")
    
    while True:
        session_id = get_instagram_session()
        
        # Ask if user wants to add another account
        choice = input("\nAdd another account? (y/n): ").lower()
        if choice != 'y':
            break
    
    print("\nAll sessions saved to 'sessions.txt'")
    print("Exiting program...")

if __name__ == "__main__":
    main()