# Telegram Session Login, Bot Onboarding Guide & Legal Compliance Implementation Plan

## Goal Description
Enhance **TGBOT Builder** with a modern, friction-free login and onboarding experience while ensuring full compliance with the **Google Play Store policies** and **Indian Information Technology Laws (IT Act 2000, IT Rules 2021, and DPDP Act 2023)**:

1. **Animated Login Screen Overhaul**:
   - Modern glassmorphism UI with smooth gradient pulse / wave animations.
   - **Removal of Guest Login** to ensure authenticated user accountability on Google Play.
   - **Option 1: Login with Telegram Session (MTProto)**:
     - Phone number input (+91 country code pre-filled for Indian users or international selector).
     - Telegram verification code (OTP) sent directly inside Telegram app.
     - Two-Step Verification (Cloud 2FA password) prompt if enabled on Telegram account.
     - **Auto Bot Discovery**: When logged in with Telegram Session, the server queries `@BotFather` directly via MTProto, discovering all bots created by the user so they can select their bot with **1-tap without copy-pasting any token**!
   - **Option 2: Login via Telegram Web / Bot Auth**:
     - Fast OAuth / Telegram Widget authorization.
   - **Option 3: Email & Password Sign In / Sign Up**:
     - Retained as a fallback option.
2. **First-Time Bot Onboarding & Interactive Guide Screen**:
   - If a user has no bots added yet (`bots.isEmpty()`), redirect to a dedicated onboarding screen rather than an empty dashboard.
   - If session-authenticated: Displays auto-discovered bots list to select with 1 tap.
   - If token-authenticated: Provides an **Interactive Visual Step-by-Step Guide**:
     - Step 1: Open `@BotFather` with direct Telegram deep link (`https://t.me/BotFather`).
     - Step 2: Send `/newbot`, assign bot name and `@username`.
     - Step 3: Copy HTTP API Token (`123456:ABC...`).
     - Step 4: Paste & Verify token with live auto-fetch.
   - Once a bot is connected, transitions into the Main Dashboard.
3. **Indian Legal & Play Store Compliance (IT Act, 2000 & DPDP Act, 2023)**:
   - Mandatory Consent Checkbox before login.
   - Interactive Terms & Conditions and Privacy Policy viewer dialog + hosted web page.
   - Clear disclosure that Telegram Session is strictly used for bot metadata fetching from `@BotFather` and never reads personal messages.
   - Grievance Officer details (Mandatory under Indian IT Intermediary Rules, 2021).
   - In-app Account Deletion mechanism (Google Play Store compliance).

---

## User Flow Diagram

```mermaid
flowchart TD
    Start["User Opens App"] --> CheckAuth{"Is User Logged In?"}
    
    CheckAuth -- No --> LoginScreen["Animated Login Screen<br/>(Telegram Session / Telegram Web / Email)"]
    
    LoginScreen --> MethodChoice{"Select Method"}
    MethodChoice -- Telegram Session --> PhoneInput["Enter Phone Number (+91...)"]
    PhoneInput --> OtpInput["Enter Telegram OTP (+ 2FA if set)"]
    OtpInput --> SessionVerify["Verify & Issue User JWT"]
    
    MethodChoice -- Telegram Web/OAuth --> WebVerify["Authenticate & Issue JWT"]
    MethodChoice -- Email/Password --> EmailVerify["Authenticate & Issue JWT"]
    
    SessionVerify --> CheckBots{"Has Connected Bots?"}
    WebVerify --> CheckBots
    EmailVerify --> CheckBots
    CheckAuth -- Yes --> CheckBots
    
    CheckBots -- No (First Time) --> OnboardingChoice{"Session Logged In?"}
    OnboardingChoice -- Yes --> AutoDiscover["Auto-Discover Bots from @BotFather<br/>(Tap to Select Bot)"]
    OnboardingChoice -- No --> VisualGuide["Step-by-Step @BotFather Tutorial<br/>(Paste Token Input)"]
    
    AutoDiscover --> ConnectBot["Bot Activated on VPS"]
    VisualGuide --> ConnectBot
    
    ConnectBot --> DashboardScreen["TGBOT Builder Dashboard<br/>(Metrics, Modules Hub, Analytics)"]
    CheckBots -- Yes --> DashboardScreen
```

---

## User Review Required

> [!IMPORTANT]
> **Telegram MTProto Session Client**:
> To support Login with Telegram Session and `@BotFather` auto-bot discovery, the VPS backend uses **Telethon** (`telethon` Python package). Telegram requires an `api_id` and `api_hash` from `my.telegram.org`. We will configure standard Telegram credentials on the VPS backend.

> [!TIP]
> **Indian IT Act & DPDP Act 2023 Compliance**:
> A compliant Privacy Policy and Terms of Service document must name a **Grievance Officer** (e.g., `Grievance Officer, TGBOT Builder, support@yourdomain.com`). We will provide a clean template with statutory Indian IT disclosures that users can inspect directly in the app.

---

## Proposed Changes

### Component 1: VPS Backend Service (`/root/telegram-saas`)

#### [NEW] `modules/identity/telegram_session_service.py`
Telethon-based service handling:
- `send_login_code(phone: str)` ➔ Returns `phone_code_hash`.
- `verify_login_code(phone: str, code: str, phone_code_hash: str, password: Optional[str])` ➔ Signs in user, generates/retrieves User in DB, stores encrypted session string, and issues JWT tokens.
- `discover_user_bots(session_string: str)` ➔ Connects to `@BotFather` via MTProto, sends `/mybots`, parses all user bots and their HTTP tokens, returning a clean list of bots ready for 1-tap activation.

#### [MODIFY] `apps/api/routes/auth.py`
Add endpoints:
- `POST /api/v1/auth/telegram-session/send-code`: Send OTP to Telegram app.
- `POST /api/v1/auth/telegram-session/verify`: Complete OTP and 2FA verification.
- `GET /api/v1/auth/telegram-session/my-bots`: Retrieve auto-discovered bots for connected session.

#### [NEW] `static/legal/terms.html` & `static/legal/privacy.html`
- Formatted legal terms compliant with Indian IT Act 2000, IT Rules 2021, and DPDP Act 2023.

---

### Component 2: Android App Presentation (`composeApp`)

#### [MODIFY] `core/ui/.../navigation/Screen.kt`
- Add `data object BotOnboardingScreen : Screen()`

#### [MODIFY] `composeApp/.../presentation/auth/LoginRegisterScreen.kt`
- **Visuals**:
  - Add animated gradient wave / pulse background.
  - Sleek Material 3 glassmorphism card.
- **Login Tabs / Modes**:
  1. **Telegram Session (Instant Connect)**:
     - Phone number input (+91 pre-filled, editable).
     - OTP input field (revealed after code sent).
     - 2FA Password field (revealed if user has cloud 2FA enabled).
     - "Send OTP" and "Verify & Login" buttons.
  2. **Telegram Web / Bot Auth**:
     - Fast 1-tap Telegram authentication.
  3. **Email / Password**:
     - Clean fallback for standard email accounts.
- **Guest Login Removal**:
  - Remove "Explore as Guest" button completely to comply with authenticated user requirements.
- **Indian Legal Consent**:
  - Checkbox: "I agree to Terms & Conditions and Privacy Policy (Governed by Indian IT Act, 2000 & DPDP Act 2023)".
  - Clickable links opening `LegalTermsDialog`.

#### [NEW] `composeApp/.../presentation/auth/LegalTermsDialog.kt`
- In-app modal viewer displaying:
  - Terms & Conditions (Governing Law: India).
  - Privacy Policy (DPDP Act 2023 disclosures).
  - Explicit Telegram Session Data Security Guarantee (only queries `@BotFather`, zero access to private messages).
  - Grievance Redressal Mechanism & Officer contact info.

#### [NEW] `composeApp/.../presentation/onboarding/BotOnboardingScreen.kt`
- Rendered when `isUserLoggedIn == true` and `bots.isEmpty()`.
- **Mode A (If Session Logged In)**:
  - Shows "Auto-Discovered Bots from your Telegram Account":
  - Card list of bots with `@username` and "Connect" button.
  - 1-tap activation.
- **Mode B (If Manual / Token Guided)**:
  - Carousel / Stepper tutorial:
    - Step 1: Open `@BotFather` button (`https://t.me/BotFather`).
    - Step 2: Visual guide showing `/newbot` command.
    - Step 3: Copy token banner.
    - Step 4: Token input field with live `getMe` verification.
  - "Save & Open Dashboard" button.

#### [MODIFY] `composeApp/.../MyBrainApp.kt` & `NavigationGraph.kt`
- Route navigation: If user is logged in, check `bots.isEmpty()`.
  - If `bots.isEmpty()` ➔ Navigate to `Screen.BotOnboardingScreen`.
  - If `bots.isNotEmpty()` ➔ Navigate to `Screen.Main` (Dashboard).

#### [MODIFY] `composeApp/.../data/api/TgBotBackendService.kt`
- Add methods for:
  - `sendTelegramSessionCode(phone)`
  - `verifyTelegramSessionCode(phone, code, hash, password)`
  - `discoverSessionBots(token)`

---

## Verification Plan

### 1. Automated Backend Verification
```bash
# Test session code dispatch
curl -X POST http://148.113.1.66:8000/api/v1/auth/telegram-session/send-code \
  -H "Content-Type: application/json" \
  -d '{"phone_number": "+919876543210"}'
```
- Verify response returns `phone_code_hash`.

### 2. Android App Compilation & Verification
```bash
cd /root/MyBrain && ./gradlew :androidApp:assembleDebug
```
- Verify zero compiler warnings or broken navigation routes.
- Confirm APK generated at `/root/TGBOT-Builder.apk`.

### 3. Manual Verification Flow
1. Launch App ➔ Verify Animated Login Screen displays without Guest option.
2. Tap "Terms & Privacy" ➔ Verify Indian IT Act 2000 & DPDP Act 2023 compliance dialog opens.
3. Test Login via Telegram Session:
   - Enter phone number ➔ Receive code inside Telegram app.
   - Enter OTP (and 2FA if set) ➔ Success.
4. Verify Bot Onboarding Screen opens automatically:
   - Verify `@BotFather` auto-discovered bots appear (or step-by-step visual guide displays).
   - Select or add bot ➔ Verify bot is saved on VPS and user lands on the Dashboard.
