Sure! Below is a comprehensive, step-by-step guide to help you implement the entire application as described. This guide covers setting up the backend with NestJS, integrating it with Together AI, Firebase Auth, Wasabi S3, and Memgraph (Neo4j). Then, we'll set up the frontend using Vite with the `ts-node` template and integrate it with the backend using Swagger Codegen.

**Note:** Please make sure to replace placeholder values (like API keys, secrets, and endpoints) with your actual credentials. Do not share your actual keys publicly.

---

## Table of Contents

1. [Prerequisites](#prerequisites)
2. [Backend Implementation](#backend-implementation)
   - [1. Initialize NestJS Project](#1-initialize-nestjs-project)
   - [2. Install Dependencies](#2-install-dependencies)
   - [3. Setup Firebase Authentication](#3-setup-firebase-authentication)
   - [4. Setup Together AI Integration](#4-setup-together-ai-integration)
   - [5. Setup Wasabi S3 for Image Storage](#5-setup-wasabi-s3-for-image-storage)
   - [6. Setup Memgraph (Neo4j) Database](#6-setup-memgraph-neo4j-database)
   - [7. Implement Backend Logic](#7-implement-backend-logic)
   - [8. Setup Swagger for API Documentation](#8-setup-swagger-for-api-documentation)
3. [Frontend Implementation](#frontend-implementation)
   - [1. Initialize Vite Project](#1-initialize-vite-project)
   - [2. Install Dependencies](#2-install-dependencies-frontend)
   - [3. Generate API Client using Swagger Codegen](#3-generate-api-client-using-swagger-codegen)
   - [4. Setup Firebase Authentication on Frontend](#4-setup-firebase-authentication-frontend)
   - [5. Implement Frontend Components](#5-implement-frontend-components)
4. [Running the Application](#running-the-application)
5. [Conclusion](#conclusion)

---

## Prerequisites

- **Node.js and Yarn:** Make sure you have Node.js and Yarn installed.
- **NestJS CLI:** Install globally via `yarn global add @nestjs/cli`
- **Firebase Account:** Setup a Firebase project for authentication.
- **Together AI API Key:** Sign up and obtain an API key.
- **Wasabi S3 Account:** Sign up and get access keys.
- **Memgraph (Neo4j) Database:** Set up a Memgraph instance. Alternatively, you can use Neo4j for development.
- **Stripe Account:** For handling payments.

---

## Backend Implementation

### 1. Initialize NestJS Project

```bash
mkdir ai-image-generator-backend
cd ai-image-generator-backend
nest new .
```

Choose **Yarn** as the package manager when prompted.

### 2. Install Dependencies

```bash
yarn add firebase-admin @nestjs/passport passport passport-firebase-jwt together-ai @aws-sdk/client-s3 neo4j-driver @nestjs/swagger swagger-ui-express stripe
yarn add -D @types/passport-firebase-jwt @types/passport
```

### 3. Setup Firebase Authentication

#### a. Initialize Firebase Admin SDK

Create a `firebase` folder within the `src` directory and add `firebase.service.ts`.

```typescript
// src/firebase/firebase.service.ts
import { Injectable } from '@nestjs/common';
import * as admin from 'firebase-admin';

@Injectable()
export class FirebaseService {
  constructor() {
    admin.initializeApp({
      credential: admin.credential.applicationDefault(),
    });
  }

  async verifyToken(token: string) {
    return admin.auth().verifyIdToken(token);
  }
}
```

#### b. Create Authentication Guard

```typescript
// src/auth/firebase-auth.guard.ts
import { Injectable, ExecutionContext } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class FirebaseAuthGuard extends AuthGuard('firebase-jwt') {
  canActivate(context: ExecutionContext) {
    return super.canActivate(context);
  }
}
```

#### c. Implement Passport Strategy

```typescript
// src/auth/firebase.strategy.ts
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-firebase-jwt';
import { FirebaseService } from '../firebase/firebase.service';

@Injectable()
export class FirebaseStrategy extends PassportStrategy(Strategy, 'firebase-jwt') {
  constructor(private readonly firebaseService: FirebaseService) {
    super({
      jwtFromRequest: (req) => {
        if (req && req.headers.authorization) {
          return req.headers.authorization.split(' ')[1];
        }
        return null;
      },
    });
  }

  async validate(token: string) {
    const firebaseUser = await this.firebaseService.verifyToken(token);
    return firebaseUser;
  }
}
```

#### d. Register Auth Module

```typescript
// src/auth/auth.module.ts
import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { FirebaseStrategy } from './firebase.strategy';
import { FirebaseService } from '../firebase/firebase.service';

@Module({
  imports: [PassportModule],
  providers: [FirebaseStrategy, FirebaseService],
})
export class AuthModule {}
```

### 4. Setup Together AI Integration

Install the Together AI SDK (already installed above).

Create a service to interact with Together AI.

```typescript
// src/together-ai/together-ai.service.ts
import { Injectable } from '@nestjs/common';
import Together from 'together-ai';

@Injectable()
export class TogetherAIService {
  private together;

  constructor() {
    this.together = new Together({ apiKey: process.env.TOGETHER_AI_API_KEY });
  }

  async generateImage(prompt: string, width: number, height: number) {
    const response = await this.together.images.create({
      model: 'black-forest-labs/FLUX.1-schnell',
      prompt,
      width,
      height,
      steps: 4,
      n: 1,
      response_format: 'b64_json',
    });
    return response.data[0].b64_json;
  }
}
```

Don't forget to add the `TOGETHER_AI_API_KEY` to your environment variables.

### 5. Setup Wasabi S3 for Image Storage

Install AWS SDK for S3 (already installed).

Create a service for S3 interactions.

```typescript
// src/s3/s3.service.ts
import { Injectable } from '@nestjs/common';
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import { v4 as uuidv4 } from 'uuid';

@Injectable()
export class S3Service {
  private s3: S3Client;
  private bucket: string = process.env.S3_BUCKET;

  constructor() {
    this.s3 = new S3Client({
      region: process.env.S3_REGION,
      credentials: {
        accessKeyId: process.env.S3_ACCESS_KEY,
        secretAccessKey: process.env.S3_SECRET_KEY,
      },
      endpoint: process.env.S3_ENDPOINT,
    });
  }

  async uploadImage(buffer: Buffer): Promise<string> {
    const uuid = uuidv4();
    const key = `${uuid}.png`;

    const command = new PutObjectCommand({
      Bucket: this.bucket,
      Key: key,
      Body: buffer,
      ContentType: 'image/png',
    });

    try {
      await this.s3.send(command);
      return `${process.env.S3_PUBLIC_URL}/${key}`;
    } catch (err) {
      console.error(err);
      throw err;
    }
  }
}
```

Add the S3 configuration to your environment variables:

```env
S3_ACCESS_KEY=YOUR_S3_ACCESS_KEY
S3_SECRET_KEY=YOUR_S3_SECRET_KEY
S3_REGION=YOUR_S3_REGION
S3_ENDPOINT=YOUR_S3_ENDPOINT
S3_BUCKET=YOUR_S3_BUCKET
S3_PUBLIC_URL=YOUR_S3_PUBLIC_URL (e.g., https://aah.wituz.com)
```

### 6. Setup Memgraph (Neo4j) Database

Install Neo4j driver (already installed).

Create a service to interact with Memgraph.

```typescript
// src/database/database.service.ts
import { Injectable } from '@nestjs/common';
import neo4j from 'neo4j-driver';

@Injectable()
export class DatabaseService {
  private driver;
  private session;

  constructor() {
    this.driver = neo4j.driver(
      process.env.NEO4J_URI,
      neo4j.auth.basic(process.env.NEO4J_USER, process.env.NEO4J_PASSWORD),
    );
    this.session = this.driver.session();
  }

  async run(query: string, params?: any) {
    return this.session.run(query, params);
  }

  async close() {
    await this.session.close();
    await this.driver.close();
  }
}
```

Add the database configuration to your environment variables:

```env
NEO4J_URI=bolt://localhost:7687
NEO4J_USER=neo4j
NEO4J_PASSWORD=your_password
```

### 7. Implement Backend Logic

#### a. Define Entities

Since Memgraph/Neo4j is a graph database, we'll define User and Image nodes.

#### b. Implement Controllers and Services

Create `users` and `images` modules.

```bash
nest generate module users
nest generate controller users
nest generate service users

nest generate module images
nest generate controller images
nest generate service images
```

#### c. Users Module

Implement user-related functionality, like tracking image counts, generations, and fueling accounts.

**users.service.ts**

```typescript
// src/users/users.service.ts
import { Injectable } from '@nestjs/common';
import { DatabaseService } from '../database/database.service';

@Injectable()
export class UsersService {
  constructor(private readonly db: DatabaseService) {}

  async findOrCreateUser(uid: string, ipAddress: string) {
    const query = `
      MERGE (u:User {uid: $uid})
      ON CREATE SET u.generations = 5, u.createdAt = timestamp()
      RETURN u
    `;
    const result = await this.db.run(query, { uid });
    return result.records[0].get('u').properties;
  }

  // Additional methods to update generations, fuel the account, etc.
}
```

**users.controller.ts**

```typescript
// src/users/users.controller.ts
import { Controller, Get, Request, UseGuards } from '@nestjs/common';
import { FirebaseAuthGuard } from '../auth/firebase-auth.guard';
import { UsersService } from './users.service';

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @UseGuards(FirebaseAuthGuard)
  @Get('profile')
  async getProfile(@Request() req) {
    const user = await this.usersService.findOrCreateUser(req.user.uid, req.ip);
    return user;
  }
}
```

#### d. Images Module

Handle image generation, storage, and retrieval.

**images.service.ts**

```typescript
// src/images/images.service.ts
import { Injectable } from '@nestjs/common';
import { TogetherAIService } from '../together-ai/together-ai.service';
import { S3Service } from '../s3/s3.service';
import { UsersService } from '../users/users.service';
import { DatabaseService } from '../database/database.service';

@Injectable()
export class ImagesService {
  constructor(
    private readonly togetherAIService: TogetherAIService,
    private readonly s3Service: S3Service,
    private readonly usersService: UsersService,
    private readonly db: DatabaseService,
  ) {}

  async generateImage(uid: string, prompt: string, width: number, height: number) {
    // Check user generations left
    // Deduct one generation
    // Generate image
    const base64Image = await this.togetherAIService.generateImage(prompt, width, height);
    const buffer = Buffer.from(base64Image, 'base64');
    const imageUrl = await this.s3Service.uploadImage(buffer);

    // Save image record in database
    const query = `
      MATCH (u:User {uid: $uid})
      CREATE (i:Image {url: $url, createdAt: timestamp(), prompt: $prompt})
      CREATE (u)-[:GENERATED]->(i)
      RETURN i
    `;
    await this.db.run(query, { uid, url: imageUrl, prompt });

    return imageUrl;
  }

  // Additional methods to retrieve images, etc.
}
```

**images.controller.ts**

```typescript
// src/images/images.controller.ts
import { Controller, Post, Body, UseGuards, Request } from '@nestjs/common';
import { ImagesService } from './images.service';
import { FirebaseAuthGuard } from '../auth/firebase-auth.guard';

@Controller('images')
export class ImagesController {
  constructor(private readonly imagesService: ImagesService) {}

  @UseGuards(FirebaseAuthGuard)
  @Post('generate')
  async generateImage(@Request() req, @Body() body) {
    const { prompt, width, height } = body;
    const imageUrl = await this.imagesService.generateImage(req.user.uid, prompt, width, height);
    return { imageUrl };
  }
}
```

### 8. Setup Swagger for API Documentation

Install Swagger packages (already installed).

In `main.ts`, enable Swagger:

```typescript
// src/main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // Setup Swagger
  const config = new DocumentBuilder()
    .setTitle('AI Image Generator API')
    .setDescription('API documentation for the AI Image Generator')
    .setVersion('1.0')
    .addBearerAuth() // JWT Auth
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);

  await app.listen(3000);
}
bootstrap();
```

---

## Frontend Implementation

### 1. Initialize Vite Project

```bash
mkdir ai-image-generator-frontend
cd ai-image-generator-frontend
yarn create vite
```

Select the `ts` template when prompted.

### 2. Install Dependencies

#### Install React and Firebase

```bash
yarn add react-router-dom firebase axios
yarn add -D @types/react-router-dom
```

### 3. Generate API Client using Swagger Codegen

First, make sure your backend is running and Swagger documentation is available at `http://localhost:3000/api-json`.

#### Install Swagger Codegen CLI

```bash
yarn global add @openapitools/openapi-generator-cli
```

#### Generate API Client

```bash
openapi-generator-cli generate -i http://localhost:3000/api-json -g typescript-fetch -o src/api
```

### 4. Setup Firebase Authentication on Frontend

Initialize Firebase in your project.

**firebase.ts**

```typescript
// src/firebase.ts
import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';

const firebaseConfig = {
  apiKey: 'YOUR_FIREBASE_API_KEY',
  authDomain: 'YOUR_FIREBASE_AUTH_DOMAIN',
  // ...other config
};

const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
```

### 5. Implement Frontend Components

#### a. Main App Structure

**App.tsx**

```tsx
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { FrontPage } from './pages/FrontPage';
import { UserPage } from './pages/UserPage';
import { AuthProvider } from './contexts/AuthContext';

function App() {
  return (
    <AuthProvider>
      <Router>
        <Routes>
          <Route path="/" element={<FrontPage />} />
          <Route path="/user" element={<UserPage />} />
        </Routes>
      </Router>
    </AuthProvider>
  );
}

export default App;
```

#### b. Authentication Context

**contexts/AuthContext.tsx**

```tsx
import React, { createContext, useEffect, useState } from 'react';
import { onAuthStateChanged, User } from 'firebase/auth';
import { auth } from '../firebase';

interface AuthContextProps {
  user: User | null;
}

export const AuthContext = createContext<AuthContextProps>({ user: null });

export const AuthProvider: React.FC = ({ children }) => {
  const [user, setUser] = useState<User | null>(null);

  useEffect(() => {
    const unsub = onAuthStateChanged(auth, (firebaseUser) => {
      setUser(firebaseUser);
    });
    return () => unsub();
  }, []);

  return <AuthContext.Provider value={{ user }}>{children}</AuthContext.Provider>;
};
```

#### c. Front Page Component

**pages/FrontPage.tsx**

```tsx
import React, { useState, useContext } from 'react';
import { AuthContext } from '../contexts/AuthContext';
import { ImagesApi } from '../api/apis/ImagesApi';

export const FrontPage: React.FC = () => {
  const { user } = useContext(AuthContext);
  const [prompt, setPrompt] = useState('');
  const [imageUrl, setImageUrl] = useState('');

  const handleGenerate = async () => {
    try {
      const api = new ImagesApi();
      api.setDefaultAuthentication({
        accessToken: await user?.getIdToken(),
      });
      const response = await api.imagesControllerGenerateImage({
        prompt,
        width: 1024,
        height: 768,
      });
      setImageUrl(response.imageUrl);
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <div>
      <h1>AI Image Generator</h1>
      <input
        type="text"
        placeholder="Enter prompt"
        value={prompt}
        onChange={(e) => setPrompt(e.target.value)}
      />
      <button onClick={handleGenerate}>Generate</button>
      {imageUrl && <img src={imageUrl} alt="Generated" />}
      {!user && <button onClick={() => { /* Implement Login */ }}>Login</button>}
      {user && <a href="/user">Go to User Page</a>}
    </div>
  );
};
```

#### d. User Page Component

**pages/UserPage.tsx**

```tsx
import React, { useEffect, useState, useContext } from 'react';
import { AuthContext } from '../contexts/AuthContext';
import { UsersApi } from '../api/apis/UsersApi';
import { ImagesApi } from '../api/apis/ImagesApi';

export const UserPage: React.FC = () => {
  const { user } = useContext(AuthContext);
  const [generationsLeft, setGenerationsLeft] = useState(0);
  const [images, setImages] = useState([]);

  useEffect(() => {
    const fetchUserData = async () => {
      const api = new UsersApi();
      api.setDefaultAuthentication({
        accessToken: await user?.getIdToken(),
      });
      const profile = await api.usersControllerGetProfile();
      setGenerationsLeft(profile.generations);

      // Fetch user images...
    };

    if (user) {
      fetchUserData();
    }
  }, [user]);

  return (
    <div>
      <h1>User Page</h1>
      <p>Generations Left: {generationsLeft}</p>
      <div>
        <h2>Your Images</h2>
        {/* Render images */}
      </div>
      <button onClick={() => { /* Implement Fuel Account */ }}>Fuel Account</button>
    </div>
  );
};
```

#### e. Implement Authentication Flow

Implement login and signup using Firebase Authentication with Email, Google, or Apple.

**Implementing login is beyond the scope of this guide, but you can use Firebase UI or build custom login components.**

#### f. Styling

Style your components to have a clean and elegant design using CSS or a CSS-in-JS solution.

---

## Running the Application

### Backend

1. **Set Environment Variables:**

   Create an `.env` file in the root of your backend project with all the necessary variables.

2. **Run the Backend:**

   ```bash
   yarn start:dev
   ```

### Frontend

1. **Set Environment Variables:**

   If needed, create a `.env` file in the frontend project for Firebase configuration.

2. **Run the Frontend:**

   ```bash
   yarn dev
   ```

---

## Conclusion

You've now implemented a complete application where users can generate images from prompts using AI, manage their accounts, and purchase additional generations. The backend is powered by NestJS, Firebase Auth, Together AI, Wasabi S3, and Memgraph (Neo4j). The frontend is built with Vite, React, and integrates with the backend using Swagger Codegen.

**Next Steps:**

- **Implement Stripe Integration:** In the backend, create endpoints to handle payments using Stripe. Ensure webhooks are properly set up to update user accounts after successful payments.

- **Enhance Error Handling:** Add comprehensive error handling in both backend and frontend to handle edge cases gracefully.

- **Security Considerations:** Ensure all sensitive information is properly secured. Use HTTPS in production, and never expose API keys or secrets.

- **Testing:** Write unit and integration tests for your backend and frontend components.

---

**Final Note:** Remember to replace all placeholder values with actual configuration values specific to your setup. Always keep your API keys and secrets secure and do not commit them to version control.

If you have any questions or need further assistance, feel free to ask!