### 🧠 **Core Purpose**

The app links **Facebook Pages** to **OpenAI assistants**, listens to webhook events from Facebook (like comments or shares), and responds automatically with **AI-generated replies**. It logs all interactions for analytics or auditing.

---

### 🧩 **Key Components and Their Roles**

#### 1. **Models (`models.py`)**

* `FacebookPageAssistant`: Links a Facebook Page (`page_id`, `page_name`) to an `OpenAIAssistant`, and tracks whether it's subscribed to webhooks.
* `EventType`: Catalog of event types like `comment`, `share`.
* `FacebookEvent`: Stores each received event, with sender, message, and timestamp.

#### 2. **Webhook Entry Point (`views.py` + `urls.py`)**

* URL: `/webhook/`
* Accepts POST requests from Facebook.
* Uses `item_type` from the event payload to route to:

  * `handle_comment_event`
  * `handle_share_event`

#### 3. **Webhook Logic (`webhook_handlers.py`)**

* `verify_webhook_token`: (Not currently used in the URL) for GET verification if needed.
* `handle_comment_event`:

  * Ignores self-comments.
  * Logs event in DB.
  * Uses OpenAI assistant to generate a reply to a comment.
* `handle_share_event`:

  * Logs share event.
  * Generates a thoughtful comment on the shared post (and optionally its parent).

#### 4. **Service Layer (`services.py`)**

* **FacebookService**: Wraps Facebook Graph API calls.

  * Retrieves page access tokens.
  * Fetches post details (description, parent).
  * Posts comments or replies using OpenAI-generated responses.
  * Logs interaction in Neo4j via `Neo4jDatabase.store_interaction(...)`.

---

### 🤖 **AI Integration**

* Uses `OpenAIAssistant` from `pxy_openai` to generate context-aware replies based on:

  * Original message or description of the post.
  * The assistant's configured personality or style.
* Bot personas like “Dr. Dr. Ekaropolus” are used to create engaging, scientifically-oriented content.

---

### 🔗 **Data Flow**

```
Facebook Webhook ──▶ /webhook/
                   └─▶ parse payload
                       └─▶ handle_comment_event()
                           ├─▶ store in DB
                           ├─▶ generate reply via OpenAI
                           └─▶ post to Facebook + log to Neo4j
```

---

### 🗂️ **Persistence**

* Uses Django ORM to store:

  * Page-assistant bindings.
  * Events (comments, shares).
* Logs interactions into a Neo4j graph DB for tracing conversations or influence paths.

