PROJECT OVERVIEW:
Develop a fully functional, multi-page Next.js MVP application for 'Code Limit Guard'. This application addresses the critical problem faced by developers using AI coding assistants like Claude Code, GitHub Copilot, and others: unexpectedly hitting usage limits and draining quotas much faster than anticipated. This leads to disrupted workflows, increased costs, and frustration. Code Limit Guard provides real-time monitoring of AI token consumption, proactive alerts, and intelligent recommendations to help users manage their AI usage efficiently, stay within budget, and avoid workflow interruptions. The core value proposition is to empower developers with control and predictability over their AI coding assistant expenses and usage.
TECH STACK:
- **Framework:** Next.js (App Router)
- **Language:** TypeScript
- **Styling:** Tailwind CSS
- **ORM:** Drizzle ORM (PostgreSQL compatible, e.g., with Neon or Supabase)
- **UI Library:** shadcn/ui for pre-built, accessible components.
- **Authentication:** NextAuth.js (or Clerk for a simpler setup)
- **State Management:** React Context API or Zustand for global state, local component state as needed.
- **Form Handling:** React Hook Form with Zod for validation.
- **Charting:** Recharts or Chart.js for visualizing token consumption.
- **Database:** PostgreSQL (or a compatible Drizzle driver)
- **Deployment:** Vercel
- **API Communication:** Server Actions and Route Handlers in Next.js.
- **Other:** ESLint, Prettier for code quality.
DATABASE SCHEMA (PostgreSQL with Drizzle ORM):
1. **`users`**
* `id` (UUID, PK)
* `name` (VARCHAR)
* `email` (VARCHAR, UNIQUE, NOT NULL)
* `emailVerified` (TIMESTAMP)
* `image` (VARCHAR)
* `createdAt` (TIMESTAMP, DEFAULT now())
* `updatedAt` (TIMESTAMP, DEFAULT now())
2. **`accounts`** (for NextAuth.js)
* `id` (BIGSERIAL, PK)
* `userId` (UUID, FK to users.id)
* `type` (VARCHAR)
* `provider` (VARCHAR)
* `providerAccountId` (VARCHAR)
* `refresh_token` (TEXT)
* `access_token` (TEXT)
* `expires_at` (BIGINT)
* `token_type` (VARCHAR)
* `scope` (VARCHAR)
* `id_token` (TEXT)
* `session_state` (VARCHAR)
3. **`sessions`** (for NextAuth.js)
* `id` (BIGSERIAL, PK)
* `sessionToken` (VARCHAR, UNIQUE, NOT NULL)
* `userId` (UUID, FK to users.id)
* `expires` (TIMESTAMP, NOT NULL)
4. **`verificationTokens`** (for NextAuth.js)
* `identifier` (VARCHAR, PK)
* `token` (VARCHAR, UNIQUE, NOT NULL)
* `expires` (TIMESTAMP, NOT NULL)
5. **`aiProviders`** (e.g., OpenAI, Anthropic, Google AI)
* `id` (SERIAL, PK)
* `name` (VARCHAR, UNIQUE, NOT NULL) // e.g., 'OpenAI', 'Anthropic', 'Google'
* `baseUrl` (VARCHAR) // API base URL
6. **`userAiConnections`** (Connects users to specific AI provider accounts/APIs)
* `id` (UUID, PK, DEFAULT gen_random_uuid())
* `userId` (UUID, FK to users.id, NOT NULL)
* `providerId` (INTEGER, FK to aiProviders.id, NOT NULL)
* `apiKey` (TEXT) // Encrypted API Key
* `config` (JSONB) // e.g., model name, custom settings
* `createdAt` (TIMESTAMP, DEFAULT now())
* `updatedAt` (TIMESTAMP, DEFAULT now())
* UNIQUE (`userId`, `providerId`)
7. **`usageLimits`** (User-defined limits per provider/project)
* `id` (UUID, PK, DEFAULT gen_random_uuid())
* `userAiConnectionId` (UUID, FK to userAiConnections.id, NOT NULL)
* `limitType` (VARCHAR) // e.g., 'daily_tokens', 'monthly_cost'
* `limitValue` (INTEGER, NOT NULL)
* `currency` (VARCHAR) // e.g., 'USD', 'EUR'
* `startTime` (TIMESTAMP) // When the limit period starts (e.g., midnight UTC for daily)
* `isActive` (BOOLEAN, DEFAULT TRUE)
* `createdAt` (TIMESTAMP, DEFAULT now())
* `updatedAt` (TIMESTAMP, DEFAULT now())
8. **`tokenUsageRecords`** (Logs actual token consumption)
* `id` (BIGSERIAL, PK)
* `userAiConnectionId` (UUID, FK to userAiConnections.id, NOT NULL)
* `timestamp` (TIMESTAMP, DEFAULT now())
* `tokensInput` (INTEGER, NOT NULL) // Tokens consumed by the prompt
* `tokensOutput` (INTEGER, NOT NULL) // Tokens generated by the AI
* `totalTokens` (INTEGER, GENERATED ALWAYS AS (tokensInput + tokensOutput) STORED) // Derived field
* `cost` (DECIMAL(10, 6)) // Estimated cost based on provider pricing
* `modelUsed` (VARCHAR)
* `apiCallDetails` (JSONB) // Optional: endpoint, parameters, etc.
CORE FEATURES & USER FLOW:
1. **Authentication & Onboarding:**
* **Flow:** User signs up using email/password or OAuth (Google, GitHub).
* On first login, user is guided to the 'Connections' page.
* User selects an AI provider (e.g., Anthropic) and enters their API Key.
* The system validates the API key by making a test call (e.g., a simple model completion request) and stores the encrypted key in `userAiConnections`.
* User is prompted to set initial usage limits (`usageLimits`) for their connection (e.g., 'daily_tokens' for Claude Code).
2. **AI Connection Management:**
* **UI:** A dedicated 'Connections' page displays all connected AI services.
* **Functionality:** Users can add new connections (enter API key), view existing connections, edit settings (e.g., model), and delete connections.
* **Security:** API keys are stored encrypted. Sensitive data handling is paramount.
3. **Real-time Token Monitoring:**
* **Backend:** A background service/cron job (or triggered via webhooks if available) periodically fetches usage data from connected AI provider APIs (using the stored `apiKey`). Alternatively, if the provider offers a callback/webhook for usage events, that would be preferred.
* **Data Storage:** Fetched usage data (input tokens, output tokens, timestamp, estimated cost) is stored in the `tokenUsageRecords` table.
* **Frontend:** The Dashboard page fetches aggregated usage data for the current period (day/month) for each connection.
4. **Limit Setting & Alerts:**
* **UI:** Within the 'Connections' or 'Limits' section, users can define multiple limits (`usageLimits`) for each connection (e.g., Daily Max Tokens, Monthly Max Cost).
* **Logic:** A scheduled job or a check after each `tokenUsageRecord` insertion compares current aggregated usage against defined limits.
* **Alerting:** If a threshold (e.g., 80% of daily limit) or the limit itself is reached, an in-app notification is displayed, and an email alert is sent to the user.
* **Turkish Translations:**