from facebook_business.api import FacebookAdsApi
from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.campaign import Campaign
from facebook_business.adobjects.adaccountuser import AdAccountUser
import os
import requests
import json
import re

# --- Configuration ---
CREDENTIALS_FILE = "facebook_ads_credentials.md"
ACCESS_TOKEN = None
APP_ID = None
APP_SECRET = None # Will be requested from user

# Read Access Token from credentials file
try:
    with open(CREDENTIALS_FILE, 'r') as f:
        content = f.read()
        match_token = re.search(r'Access Token:\s*(\S+)', content)
        if match_token:
            ACCESS_TOKEN = match_token.group(1)
        else:
            print(f"Error: Access Token not found in {CREDENTIALS_FILE}. Please ensure it's in 'Access Token: <YOUR_TOKEN>' format.")
            exit(1)
except FileNotFoundError:
    print(f"Error: Credentials file '{CREDENTIALS_FILE}' not found.")
    exit(1)

if not ACCESS_TOKEN:
    print("Error: Access Token is empty. Please check your credentials file.")
    exit(1)

# --- Main Logic ---
def main(app_id, app_secret):
    global APP_ID, APP_SECRET
    APP_ID = app_id
    APP_SECRET = app_secret

    if not APP_ID or not APP_SECRET:
        print("Error: App ID and App Secret are required to initialize the Facebook Business SDK.")
        return

    print("Initializing Facebook Business SDK...")
    FacebookAdsApi.init(app_id=APP_ID, app_secret=APP_SECRET, access_token=ACCESS_TOKEN)

    print("Fetching Facebook Ads data using SDK...")

    try:
        # Get current user's ad accounts
        print("\n--- Ad Accounts ---")
        me = AdAccountUser(fbid='me')
        user_accounts = me.get_ad_accounts(fields=[AdAccount.Field.id, AdAccount.Field.name, AdAccount.Field.account_status])
        
        ad_account_ids = []
        if user_accounts:
            for account in user_accounts:
                print(f"  ID: {account['id']}, Name: {account['name']}, Status: {account['account_status']}")
                ad_account_ids.append(account['id'])
        else:
            print("  No ad accounts found for the current user.")
            
        if not ad_account_ids:
            print("  Cannot proceed without ad accounts. Please ensure your token has access to ad accounts.")
            return

        # Fetch campaigns for each ad account
        for account_id in ad_account_ids:
            print(f"\n--- Campaigns for Ad Account: {account_id} ---")
            account = AdAccount(account_id)
            campaigns = account.get_campaigns(fields=[Campaign.Field.id, Campaign.Field.name, Campaign.Field.status, Campaign.Field.objective])
            if campaigns:
                for campaign in campaigns:
                    print(f"  ID: {campaign['id']}, Name: {campaign['name']}, Status: {campaign['status']}, Objective: {campaign['objective']}")
            else:
                print(f"  No campaigns found for ad account {account_id}.")

    except Exception as e:
        print(f"An unexpected error occurred: {e}")

if __name__ == "__main__":
    # In a real scenario, these would be passed securely, e.g., via environment variables
    # For now, we'll ask the user.
    # Placeholder values for demonstration
    APP_ID_PLACEHOLDER = os.environ.get('FB_APP_ID')
    APP_SECRET_PLACEHOLDER = os.environ.get('FB_APP_SECRET')

    if not APP_ID_PLACEHOLDER or not APP_SECRET_PLACEHOLDER:
        print("Please provide your Facebook App ID and App Secret to proceed.")
        print("You can find these in your Facebook for Developers App Dashboard, under 'Settings' -> 'Basic'.")
        # In this interactive mode, we'd wait for user input.
        # For programmatic execution, these should be set as environment variables.
        exit(1) # Exit for now, expecting user to provide.

    main(APP_ID_PLACEHOLDER, APP_SECRET_PLACEHOLDER)

