# Credentials Setup Guide

This guide provides instructions on how to set up API credentials and tokens for the various platforms supported by `sm-tracker`.

## Threads

The Threads API uses OAuth 2.0. To track Threads follower counts, you must create a Meta App and generate a long-lived access token.

### Step 1: Create a Meta App

1. Go to the [Meta Developer Portal](https://developers.facebook.com/).
2. Create a new App. Select **"Other"** as the Use Case, then select **"None"** (or Business).
3. In the App Dashboard, go to **App Settings > Basic** and note down your **App ID** (`THREADS_APP_ID`) and **App Secret** (`THREADS_APP_SECRET`).

### Step 2: Configure OAuth Settings

1. In the App Dashboard, click **Add Product** and select **Threads API**.
2. Go to the **Threads API > Settings** section in the left sidebar.
3. In the **Valid OAuth Redirect URIs** field, enter exactly `https://localhost/callback`.
4. Click **Save Changes**.

### Step 3: Run the Auth Command

Use the built-in CLI command to handle the OAuth flow and generate a long-lived token.

1. Ensure your `.env` file has the `THREADS_APP_ID` and `THREADS_APP_SECRET` populated. (You can also leave `THREADS_REDIRECT_URI=https://localhost/callback` as the default).
2. Run the interactive auth command:

    ```bash
    sm-tracker auth --platform threads
    ```

3. The CLI will provide a URL. Open this URL in your web browser and authorize the app.
4. You will be redirected to an empty `https://localhost/callback` page that looks broken (this is expected).
5. Copy the _entire_ URL from your browser's address bar (it will contain a `?code=...` parameter).
6. Paste that full URL back into the CLI prompt.
7. The CLI will automatically exchange the code for a short-lived token, then exchange _that_ for a 60-day long-lived token.
8. The final `THREADS_ACCESS_TOKEN`, `THREADS_USER_ID`, and `THREADS_ACCESS_TOKEN_EXPIRES_AT_UTC` will be securely saved to your `.env` file.

_Note: Since the long-lived token expires after 60 days, you will need to re-run the `auth --platform threads` command whenever you see expiry warnings._

## Facebook and Instagram

The Meta Graph API uses different types of access tokens for Facebook and Instagram integration. This section explains the token hierarchy, how to set up your Meta App, and how to authenticate.

### The Token Hierarchy

When setting up `sm-tracker` for Facebook and Instagram, you interact with three distinct tokens:

1. **`SHORT_LIVED_USER_TOKEN`**:
    - **What it is**: The initial token you generate manually in the Graph API Explorer.
    - **Lifespan**: ~1 to 2 hours.
    - **Purpose**: Used _only_ as a stepping stone to get the long-lived tokens via the CLI `auth` command. Do not save this permanently in your `.env` file unless you are immediately running the auth command.

2. **`LONG_LIVED_USER_TOKEN`**:
    - **What it is**: Generated by exchanging your short-lived token via the API.
    - **Lifespan**: ~60 days.
    - **Purpose**: Required to access the Instagram Graph API. This token proves _you_ (the user) have authorized the app for a prolonged period.

3. **`FACEBOOK_PAGE_ACCESS_TOKEN`**:
    - **What it is**: Generated by querying your connected Facebook Pages using the long-lived user token.
    - **Lifespan**: **Never expires** (unless you change your Facebook password or manually revoke the app's access).
    - **Purpose**: Required to access Facebook Page metrics without needing to re-authenticate constantly.

### Step 1: Create a Meta Developer Account

_You must have a standard Facebook account to do this. This account must be an Admin of the Facebook Page you want to track._

1. Navigate to [developers.facebook.com](https://developers.facebook.com) in your web browser.
2. Click **"Log In"** in the top right corner and sign in with your normal Facebook credentials.
3. Click **"Get Started"** in the top right. Follow the prompt to verify your account (via phone or email) and accept the Developer Policies.

### Step 2: Create a Meta App

_Your tokens are generated by an "App". We need to create a simple one to sit between Facebook and `sm-tracker`._

1. Click **"My Apps"** in the top right corner of the Developer Portal.
2. Click the green **"Create App"** button.
3. Choose **"Other"**, click Next, and then choose **"Business"** (this gives you access to the Graph API). Click Next.
4. Enter a name like `sm-tracker` and add your contact email. Click **"Create App"**. (You may be prompted for your Facebook password).
5. Once created, go to **App Settings > Basic** in the left sidebar. Note down your **App ID** (`META_APP_ID`) and **App Secret** (`META_APP_SECRET`).

### Step 3: Grant the App "Advanced Access" to Public Features

**\*Crucial Step**: Without this, the Graph API will throw a `(#100) Object does not exist` error when `sm-tracker` tries to read your page's follower count.\*

1. In the left-hand sidebar of your App Dashboard, expand **"App Review"** and click on **"Permissions and Features"**.
2. Search for **`Page Public Metadata Access`** (or **`Page Public Content Access`**).
3. Click the **"Request Advanced Access"** or **"Get Advanced Access"** button next to it.
    - _Note: Because you are the creator and admin of this app, Meta will usually grant this immediately without requiring a manual human review._
4. Ensure the green pill icon now says **"Advanced Access"**.

### Step 4: Generate a Short-Lived User Token

_We will use the Graph API Explorer to request an initial token._

1. Click on **"Tools"** in the top navigation bar, then select **"Graph API Explorer"**.
2. On the right panel, under **"Meta App"**, ensure your newly created app (`sm-tracker`) is selected in the dropdown.
3. In the **"User or Page"** dropdown, ensure **"User Token"** is selected.
4. In the **"Permissions"** section, click **"Add a Permission"**. Add the following:
    - `pages_show_list`
    - `pages_read_engagement`
    - `instagram_basic` (if using Instagram)
    - `business_management` (if using Instagram)
5. Click the blue **"Generate Access Token"** button.
6. A Facebook login popup will appear. Continue as your user profile.
    - **_Crucial Step_**: When it asks what pages/accounts the app can access, you MUST either leave **"Opt in to all current and future Pages"** checked, or click "Edit Settings" and specifically check the box next to your target Page and Instagram account.
    - Click **"Save"** and **"Got It"** to close the popup.
7. Copy the short string in the "Access Token" box at the very top. This is your `META_USER_TOKEN_SHORT_LIVED`.

### Facebook Integration

To fully configure Facebook tracking:

1. Ensure you have your `META_APP_ID`, `META_APP_SECRET`, and `META_USER_TOKEN_SHORT_LIVED` ready.
2. Run the interactive auth command:

    ```bash
    sm-tracker auth --platform facebook
    ```

3. The CLI will securely prompt you for the above three values (if they are not already in your `.env` file).
4. The CLI will automatically exchange the short-lived token for a long-lived user token, and then use _that_ to fetch a non-expiring `FACEBOOK_PAGE_ACCESS_TOKEN` for your page.
5. The final token is saved directly to your `.env` file. You do **not** need to manually find or enter your numeric `FACEBOOK_ID`; the tracker will securely look up the ID natively at runtime.

### Instagram Integration

To fully configure Instagram tracking:

1. **Account Prerequisites:**
    - Your Instagram account _must_ be converted to a Professional (Creator or Business) account in the Instagram mobile app settings.
    - You must have a published Facebook Page (it can be empty).
2. **Meta Business Suite Linking (Critical Step):**
    - Linking the Instagram account via the standard Facebook Page UI or the Instagram app is often insufficient. It must be linked via Meta Business Suite.
    - Navigate to **Meta Business Suite** (`business.facebook.com`).
    - Go to **Settings** -> **Accounts**.
    - Under **Pages**, select your Page and click **Connect assets**. Explicitly link the Instagram account asset to the Page asset.
3. Run the interactive auth command:

    ```bash
    sm-tracker auth --platform instagram
    ```

4. The CLI will securely prompt you for your Meta credentials (if not already in `.env`) and exchange your short-lived token for a 60-day `LONG_LIVED_USER_TOKEN`.
5. You must manually find your `INSTAGRAM_ACCOUNT_ID`. In the Graph API Explorer (with your user token), query:
   `me/accounts?fields=instagram_business_account,name`
   Locate the `"instagram_business_account"` object in the JSON response. The `"id"` within this object is the required `INSTAGRAM_ACCOUNT_ID` to put in your `.env`.
