# C++ Build Assistant Guide

## Overview

The C++ Build Assistant is a JavaScript/TypeScript-based automation tool that simplifies building, testing, and managing C++ projects using modern build tools (Conan + Ninja + CMake).

## Why This Approach?

**Problem**: C++ builds are complex and require coordinating multiple tools (package managers, build systems, compilers)

**Solution**: A lightweight JavaScript wrapper that:
- ✅ Works in Node.js environments (like GitHub Spark)
- ✅ Automates dependency installation via Conan
- ✅ Configures CMake with Ninja for fast builds
- ✅ Provides simple npm scripts for common tasks
- ✅ Checks prerequisites and guides installation
- ✅ Integrates cleanly with CI/CD pipelines

## Architecture

```
MetaBuilder/
├── dbal/                          # Database Abstraction Layer
│   ├── cpp/                       # C++ implementation (production)
│   │   ├── CMakeLists.txt        # CMake build definition
│   │   ├── conanfile.txt         # Conan dependencies
│   │   ├── include/              # Public headers
│   │   ├── src/                  # Implementation
│   │   │   ├── daemon/           # IPC daemon for secure DB access
│   │   │   └── adapters/         # SQLite, MongoDB adapters
│   │   └── build/                # Generated by build assistant
│   ├── ts/                        # TypeScript implementation (dev)
│   └── tools/
│       ├── cpp-build-assistant.js     # Node.js build automation
│       ├── cpp-build-assistant.ts     # TypeScript version
│       └── BUILD_ASSISTANT_README.md  # Detailed docs
└── package.json                   # npm scripts for C++ builds
```

## Installation

### Step 1: Install System Dependencies

#### macOS
```bash
brew install cmake conan ninja gcc
```

#### Linux (Ubuntu/Debian)
```bash
sudo apt-get install cmake ninja-build g++
pip install conan
```

#### Windows
```bash
choco install cmake conan ninja
```

### Step 2: Verify Installation

```bash
npm run cpp:check
```

This will check for:
- ✅ CMake
- ✅ Conan
- ✅ Ninja
- ✅ GCC/Clang

## Quick Start

### First Time Setup

```bash
# Run the complete workflow
npm run cpp:full
```

This executes:
1. Dependency check
2. Conanfile initialization
3. Conan package installation
4. CMake configuration
5. Ninja build

### Daily Development

```bash
# After changing C++ code
npm run cpp:build

# After changing dependencies in conanfile.txt
npm run cpp:install
npm run cpp:configure
npm run cpp:build

# Run tests
npm run cpp:test

# Clean rebuild
npm run cpp:rebuild
```

## Available Commands

### Core Commands

| Command | Description | Usage |
|---------|-------------|-------|
| `cpp:check` | Verify dependencies installed | `npm run cpp:check` |
| `cpp:init` | Create conanfile.txt | `npm run cpp:init` |
| `cpp:install` | Install Conan dependencies | `npm run cpp:install` |
| `cpp:configure` | Configure CMake with Ninja | `npm run cpp:configure` |
| `cpp:build` | Build all targets | `npm run cpp:build` |
| `cpp:test` | Run CTest suite | `npm run cpp:test` |
| `cpp:clean` | Remove build directory | `npm run cpp:clean` |
| `cpp:rebuild` | Clean + configure + build | `npm run cpp:rebuild` |
| `cpp:full` | Complete workflow | `npm run cpp:full` |

### Advanced Usage

```bash
# Build specific target
npm run cpp:build -- build dbal_daemon

# Debug build
npm run cpp:build -- build --debug

# Control parallelism
npm run cpp:build -- build --jobs=4

# Build with options
npm run cpp:build -- configure --debug
npm run cpp:build -- build dbal_core
```

## Conan Dependencies

The `conanfile.txt` specifies C++ dependencies:

```txt
[requires]
sqlite3/3.45.0          # Embedded database
fmt/10.2.1              # String formatting
spdlog/1.13.0           # Logging library
nlohmann_json/3.11.3    # JSON parsing

[generators]
CMakeDeps               # CMake integration
CMakeToolchain          # Toolchain file

[options]
sqlite3:shared=False    # Static linking

[layout]
cmake_layout            # Standard layout
```

### Adding Dependencies

1. Edit `dbal/cpp/conanfile.txt`
2. Add package to `[requires]` section
3. Run:
```bash
npm run cpp:install
npm run cpp:configure
npm run cpp:build
```

### Finding Packages

```bash
# Search Conan Center
conan search boost --remote=conancenter

# Get package info
conan inspect boost/1.82.0
```

## CMake Integration

The build assistant automatically:
- Generates `conan_toolchain.cmake`
- Configures CMake with Ninja generator
- Sets build type (Debug/Release)
- Exports `compile_commands.json` for IDE integration

### CMakeLists.txt Structure

```cmake
cmake_minimum_required(VERSION 3.20)
project(dbal VERSION 1.0.0 LANGUAGES CXX)

# Conan provides dependencies automatically
find_package(sqlite3 REQUIRED)
find_package(fmt REQUIRED)
find_package(spdlog REQUIRED)
find_package(nlohmann_json REQUIRED)

# Define targets
add_library(dbal_core STATIC ...)
add_executable(dbal_daemon ...)

# Link Conan packages
target_link_libraries(dbal_daemon
    dbal_core
    sqlite3::sqlite3
    fmt::fmt
    spdlog::spdlog
    nlohmann_json::nlohmann_json
)
```

## Testing

The assistant integrates with CTest:

```bash
# Run all tests
npm run cpp:test

# Run specific test
cd dbal/cpp/build
ctest -R unit_tests -V

# Run with output
ctest --output-on-failure
```

### Test Structure

```cpp
// tests/unit/client_test.cpp
#include "dbal/client.hpp"
#include <cassert>

int main() {
    dbal::Client client;
    assert(client.connect("test.db"));
    return 0;
}
```

## CI/CD Integration

### GitHub Actions

```yaml
name: C++ Build

on: [push, pull_request]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Install dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y cmake ninja-build g++
          pip install conan
      
      - name: Check dependencies
        run: npm run cpp:check
      
      - name: Build C++ project
        run: npm run cpp:full
      
      - name: Run tests
        run: npm run cpp:test
```

## Troubleshooting

### Conan Profile Missing

**Error**: `ERROR: Conan profile not detected`

**Fix**:
```bash
conan profile detect --force
```

### Ninja Not Found

**Error**: `CMake Error: CMake was unable to find a build program corresponding to "Ninja"`

**Fix**:
```bash
# Verify Ninja is installed
which ninja

# Add to PATH if needed
export PATH=$PATH:/path/to/ninja
```

### Build Failures

**Error**: Various build errors

**Fix**:
```bash
# Clean rebuild
npm run cpp:clean
npm run cpp:full

# Or manually
cd dbal/cpp
rm -rf build
conan install . --output-folder=build --build=missing
cmake -B build -G Ninja .
cmake --build build
```

### Conan Package Not Found

**Error**: `ERROR: Unable to find 'package/version' in remotes`

**Fix**:
```bash
# Add Conan Center remote
conan remote add conancenter https://center.conan.io

# Update remotes
conan remote list
conan remote update conancenter https://center.conan.io
```

## Performance Tips

### Parallel Builds

```bash
# Use all CPU cores (default)
npm run cpp:build

# Limit parallelism
npm run cpp:build -- build --jobs=4
```

### Incremental Builds

Ninja automatically handles incremental builds:
```bash
# Only rebuilds changed files
npm run cpp:build
```

### Compiler Cache

Use `ccache` to speed up rebuilds:
```bash
# Install ccache
brew install ccache  # macOS
sudo apt-get install ccache  # Linux

# Configure
export CMAKE_CXX_COMPILER_LAUNCHER=ccache
npm run cpp:configure
```

## IDE Integration

### Visual Studio Code

1. Install extensions:
   - C/C++ (Microsoft)
   - CMake Tools
   
2. The build assistant generates `compile_commands.json` automatically

3. Configure `.vscode/settings.json`:
```json
{
  "cmake.configureArgs": [
    "-DCMAKE_TOOLCHAIN_FILE=${workspaceFolder}/dbal/cpp/build/conan_toolchain.cmake"
  ],
  "cmake.buildDirectory": "${workspaceFolder}/dbal/cpp/build",
  "C_Cpp.default.compileCommands": "${workspaceFolder}/dbal/cpp/build/compile_commands.json"
}
```

### CLion

CLion automatically detects CMake projects. Configure:
1. Settings → Build → CMake
2. Add toolchain file: `dbal/cpp/build/conan_toolchain.cmake`
3. Generator: Ninja

## DBAL Architecture Context

The C++ build assistant supports the **Phase 2 Hybrid Mode** architecture:

```
Phase 2: Hybrid Mode (Current)
├── TypeScript DBAL (development/client)
│   └── Fast iteration, GitHub Spark integration
└── C++ Daemon (production/server)
    ├── Secure database access
    ├── Performance-critical operations
    └── Built via this assistant
```

### Why C++ Daemon?

1. **Security**: Users don't get direct DB access
2. **Performance**: Native code for intensive operations
3. **Isolation**: Separate process boundary
4. **Control**: Fine-grained access control

### Integration Pattern

```
GitHub Spark App (Browser)
    ↓ (TypeScript DBAL Client)
WebSocket/HTTP
    ↓
C++ Daemon (Built with this assistant)
    ↓
Database (SQLite/MongoDB/etc.)
```

## Related Documentation

- [DBAL Project Overview](../dbal/PROJECT.md)
- [Phase 2 Implementation](../dbal/PHASE2_IMPLEMENTATION.md)
- [C++ Daemon Design](../dbal/cpp/PHASE3_DAEMON.md)
- [Build Assistant README](../dbal/tools/BUILD_ASSISTANT_README.md)

## Examples

### Example 1: Fresh Build

```bash
# Clone project
git clone <repo>
cd project

# Install npm dependencies
npm install

# Check C++ dependencies
npm run cpp:check

# If missing, install (macOS example)
brew install cmake conan ninja

# Full C++ build
npm run cpp:full
```

### Example 2: Adding a Feature

```bash
# 1. Write C++ code
vim dbal/cpp/src/adapters/postgres/postgres_adapter.cpp

# 2. Add dependency if needed
vim dbal/cpp/conanfile.txt
# Add: libpq/15.0

# 3. Update CMakeLists.txt
vim dbal/cpp/CMakeLists.txt

# 4. Rebuild
npm run cpp:install
npm run cpp:configure
npm run cpp:build

# 5. Test
npm run cpp:test
```

### Example 3: Debugging Build Issues

```bash
# Enable verbose output
cd dbal/cpp
cmake --build build --verbose

# Check Conan setup
conan install . --output-folder=build --build=missing -v

# Verify CMake cache
cmake -L build

# Manual build
cd build
ninja -v
```

## Support

For issues:
1. Check [Troubleshooting](#troubleshooting) section
2. Review [Build Assistant README](../dbal/tools/BUILD_ASSISTANT_README.md)
3. Check Conan docs: https://docs.conan.io
4. Check CMake docs: https://cmake.org/documentation
5. Check Ninja docs: https://ninja-build.org/manual.html

## License

See LICENSE file in repository root.
