#!/usr/bin/env python3
"""
Create GitHub Project for archie-dev with EPICs and sub-issues.
This script creates a comprehensive project structure without writing any code.
"""

import json
import os
import subprocess
import sys
import time
from typing import Dict, List

# GitHub organization and repository
GITHUB_ORG = "heyarchie-ai"
GITHUB_REPO = "archie-dev"
PROJECT_TITLE = "archie-dev: AI-Driven Service Development Platform v2"

# EPIC definitions with detailed sub-issues
EPICS = [
    {
        "title": "EPIC 1: Foundation & Infrastructure",
        "description": """# EPIC 1: Foundation & Infrastructure

## Overview
Establish the foundational architecture for archie-dev v2, including repository structure, core frameworks, authentication, and deployment infrastructure.

## Timeline
**Weeks 1-2** | **36 Story Points**

## Goals
- Initialize clean repository structure for archie-build-v2
- Set up Next.js 14+ frontend with TypeScript and Shadcn/ui
- Set up FastAPI backend with PostgreSQL support
- Implement WorkOS AuthKit for heyarchie.ai SSO authentication
- Configure Railway deployment for backend + frontend + PostgreSQL
- Establish CI/CD pipeline with automated testing
- Create development documentation

## Acceptance Criteria
- ✅ Repository initialized with proper structure
- ✅ Frontend renders homepage with authentication
- ✅ Backend API responds to health checks
- ✅ PostgreSQL database accessible from backend
- ✅ WorkOS AuthKit successfully authenticates heyarchie.ai users
- ✅ Railway deployment successful for all components
- ✅ CI/CD pipeline runs tests automatically on PR
- ✅ README and developer documentation complete

## Dependencies
None (foundational epic)

## Technical Stack
- **Frontend**: Next.js 14+, TypeScript, Tailwind CSS, Shadcn/ui
- **Backend**: FastAPI, Python 3.11+, asyncpg, SQLAlchemy
- **Database**: PostgreSQL 16
- **Authentication**: WorkOS AuthKit
- **Deployment**: Railway
- **CI/CD**: GitHub Actions

## Success Metrics
- All services deploy successfully to Railway
- Authentication flow works end-to-end
- Database migrations run successfully
- CI/CD pipeline passes all checks
""",
        "labels": ["epic", "infrastructure", "foundation"],
        "story_points": 36,
        "phase": "Phase 1",
        "sub_issues": [
            {
                "title": "Initialize archie-build-v2 Repository Structure",
                "description": """## Task: Initialize Repository Structure

### Objective
Create clean, well-organized repository structure for archie-build-v2 with proper TypeScript configuration and monorepo setup.

### Scope
- Initialize new repository `archie-build-v2`
- Set up directory structure for frontend and backend
- Configure TypeScript for frontend
- Set up Python project structure for backend
- Add .gitignore, README, LICENSE

### Directory Structure
```
archie-build-v2/
├── frontend/              # Next.js 14+ frontend
│   ├── src/
│   │   ├── app/          # App router pages
│   │   ├── components/   # React components
│   │   ├── lib/          # Utilities and helpers
│   │   └── types/        # TypeScript types
│   ├── public/           # Static assets
│   ├── package.json
│   ├── tsconfig.json
│   └── next.config.js
├── backend/              # FastAPI backend
│   ├── app/
│   │   ├── api/         # API routes
│   │   ├── models/      # Database models
│   │   ├── services/    # Business logic
│   │   └── config.py    # Configuration
│   ├── migrations/      # Database migrations
│   ├── tests/           # Backend tests
│   ├── requirements.txt
│   └── pyproject.toml
├── .github/
│   └── workflows/       # CI/CD workflows
├── docs/                # Documentation
├── README.md
└── LICENSE
```

### Acceptance Criteria
- [ ] Repository created in heyarchie-ai organization
- [ ] Directory structure matches specification
- [ ] TypeScript configured for frontend (strict mode)
- [ ] Python project structure follows best practices
- [ ] README includes project overview and setup instructions
- [ ] .gitignore configured for Node.js and Python
- [ ] MIT or Apache 2.0 license added

### Technical Tasks
1. Create new repository via GitHub CLI or API
2. Initialize frontend with `npx create-next-app@latest`
3. Initialize backend with Python project structure
4. Configure TypeScript with strict settings
5. Add comprehensive .gitignore
6. Write initial README with project goals
7. Add license file
8. Create initial commit

### Dependencies
None

### Estimated Effort
**3 Story Points** (~1-2 hours)

### Labels
`setup`, `infrastructure`, `documentation`
""",
                "labels": ["setup", "infrastructure", "documentation"],
                "story_points": 3
            },
            {
                "title": "Set Up Next.js 14+ Frontend with TypeScript and Shadcn/ui",
                "description": """## Task: Set Up Frontend Foundation

### Objective
Configure Next.js 14+ frontend with TypeScript, Tailwind CSS, and Shadcn/ui components for rapid UI development.

### Scope
- Configure Next.js 14 with App Router
- Set up TypeScript with strict type checking
- Configure Tailwind CSS
- Initialize Shadcn/ui components
- Create base layout and theme
- Set up environment configuration

### Technical Requirements
- Next.js 14.0.0+
- TypeScript 5.0+
- Tailwind CSS 3.3+
- Shadcn/ui latest
- React 18+

### Configuration Files
1. **tsconfig.json**: Strict TypeScript configuration
2. **tailwind.config.ts**: Tailwind with Shadcn theme
3. **components.json**: Shadcn/ui configuration
4. **.env.local**: Environment variables template

### Shadcn/ui Components to Install
- Button
- Card
- Table
- Badge
- Dialog
- Dropdown Menu
- Tabs
- Toast (for notifications)

### Acceptance Criteria
- [ ] Next.js 14 installed with App Router enabled
- [ ] TypeScript strict mode configured
- [ ] Tailwind CSS working with custom theme
- [ ] Shadcn/ui components installed and documented
- [ ] Base layout component created
- [ ] Dark mode support configured
- [ ] Environment variables template created
- [ ] Frontend builds without errors
- [ ] Dev server runs on localhost:3000

### Technical Tasks
1. Run `npx create-next-app@latest frontend` with TypeScript
2. Install and configure Tailwind CSS
3. Run `npx shadcn-ui@latest init`
4. Install core Shadcn/ui components
5. Create base layout component (`src/app/layout.tsx`)
6. Configure theme with dark mode support
7. Set up environment variables
8. Test build process

### Dependencies
- **Blocks**: "Initialize archie-build-v2 Repository Structure"

### Estimated Effort
**5 Story Points** (~3-4 hours)

### Labels
`frontend`, `setup`, `typescript`
""",
                "labels": ["frontend", "setup", "typescript"],
                "story_points": 5
            },
            {
                "title": "Set Up FastAPI Backend with PostgreSQL Support",
                "description": """## Task: Set Up Backend Foundation

### Objective
Configure FastAPI backend with PostgreSQL database support, async operations, and production-ready structure.

### Scope
- Set up FastAPI project structure
- Configure async PostgreSQL with asyncpg and SQLAlchemy
- Set up database migrations (Alembic)
- Create health check endpoint
- Configure logging with structlog
- Set up environment configuration

### Technical Requirements
- Python 3.11+
- FastAPI 0.109.0+
- PostgreSQL 16
- asyncpg 0.29.0+
- SQLAlchemy 2.0+ (async)
- Alembic (migrations)
- structlog (logging)
- pydantic-settings (config)

### Project Structure
```
backend/
├── app/
│   ├── __init__.py
│   ├── main.py           # FastAPI application
│   ├── config.py         # Configuration via pydantic-settings
│   ├── database.py       # Database connection management
│   ├── api/
│   │   ├── __init__.py
│   │   └── health.py     # Health check endpoint
│   ├── models/
│   │   └── __init__.py
│   └── services/
│       └── __init__.py
├── migrations/
│   └── env.py            # Alembic configuration
├── tests/
│   └── test_health.py
├── requirements.txt
├── pyproject.toml
└── .env.example
```

### Database Configuration
- Support for both local development and Railway PostgreSQL
- Connection pooling with asyncpg
- Health check for database connectivity
- Migration system with Alembic

### Acceptance Criteria
- [ ] FastAPI application runs on port 8000
- [ ] `/api/health` endpoint returns 200 OK
- [ ] PostgreSQL connection established (asyncpg)
- [ ] Database connection pooling configured
- [ ] Alembic migrations initialized
- [ ] Structured logging configured
- [ ] Environment variables loaded from .env
- [ ] Backend tests pass
- [ ] API documentation available at `/docs`

### Technical Tasks
1. Create FastAPI application structure
2. Install dependencies (FastAPI, asyncpg, SQLAlchemy, etc.)
3. Configure async PostgreSQL connection
4. Set up Alembic for migrations
5. Create health check endpoint
6. Configure structlog for JSON logging
7. Set up pydantic-settings for configuration
8. Write unit tests for health endpoint
9. Document API endpoints

### Environment Variables
```
DATABASE_URL=postgresql+asyncpg://user:pass@host:5432/db
LOG_LEVEL=INFO
LOG_FORMAT=json
PORT=8000
WORKERS=4
```

### Dependencies
- **Blocks**: "Initialize archie-build-v2 Repository Structure"

### Estimated Effort
**5 Story Points** (~3-4 hours)

### Labels
`backend`, `setup`, `database`
""",
                "labels": ["backend", "setup", "database"],
                "story_points": 5
            },
            {
                "title": "Design PostgreSQL Database Schema",
                "description": """## Task: Design PostgreSQL Database Schema

### Objective
Design comprehensive PostgreSQL database schema for services, workflows, users, and execution tracking.

### Scope
- Design `services` table (service registry)
- Design `workflow_executions` table (workflow tracking)
- Design `workflow_activities` table (activity logs)
- Design `users` table (authentication)
- Create database migration files
- Document schema with ERD

### Schema Specification

#### Table: `services`
```sql
CREATE TABLE services (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  service_id VARCHAR(255) UNIQUE NOT NULL,
  name VARCHAR(255) NOT NULL,
  description TEXT,
  spec_path VARCHAR(500),
  spec_version VARCHAR(50),
  status VARCHAR(50) NOT NULL CHECK(status IN ('planned', 'in_progress', 'completed', 'blocked', 'not_started')),
  test_coverage DECIMAL(3,2),
  completeness_score DECIMAL(3,2),
  ci_status VARCHAR(50) CHECK(ci_status IN ('passing', 'failing', NULL)),
  github_issue_number INT,
  github_pr_numbers INT[],
  last_workflow_run UUID REFERENCES workflow_executions(id),
  service_type VARCHAR(50) DEFAULT 'fastapi',
  port INT,
  helm_chart_path VARCHAR(500),
  k8s_deployed BOOLEAN DEFAULT FALSE,
  k8s_namespace VARCHAR(255),
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW(),
  created_by UUID REFERENCES users(id),
  updated_by UUID REFERENCES users(id)
);

CREATE INDEX idx_services_service_id ON services(service_id);
CREATE INDEX idx_services_status ON services(status);
CREATE INDEX idx_services_created_at ON services(created_at);
```

#### Table: `workflow_executions`
```sql
CREATE TABLE workflow_executions (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  service_id VARCHAR(255) NOT NULL REFERENCES services(service_id),
  workflow_type VARCHAR(50) NOT NULL CHECK(workflow_type IN ('analyse_spec', 'build', 'test', 'sync', 'deploy')),
  status VARCHAR(20) NOT NULL CHECK(status IN ('queued', 'running', 'paused', 'completed', 'failed', 'cancelled')),
  current_stage VARCHAR(50),
  checkpoint_data JSONB,
  started_at TIMESTAMP NOT NULL DEFAULT NOW(),
  last_heartbeat TIMESTAMP,
  completed_at TIMESTAMP,
  paused_at TIMESTAMP,
  resumed_at TIMESTAMP,
  result_data JSONB,
  error_message TEXT,
  triggered_by UUID REFERENCES users(id),
  github_issue_number INT,
  github_pr_number INT,
  github_run_id VARCHAR(255),
  attempt_number INT DEFAULT 1,
  max_attempts INT DEFAULT 3,
  duration_seconds INT,
  temporal_workflow_id VARCHAR(255),
  temporal_run_id VARCHAR(255)
);

CREATE INDEX idx_workflow_executions_service_id ON workflow_executions(service_id);
CREATE INDEX idx_workflow_executions_status ON workflow_executions(status);
CREATE INDEX idx_workflow_executions_started_at ON workflow_executions(started_at);
CREATE INDEX idx_workflow_executions_temporal_workflow_id ON workflow_executions(temporal_workflow_id);
```

#### Table: `workflow_activities`
```sql
CREATE TABLE workflow_activities (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  workflow_execution_id UUID NOT NULL REFERENCES workflow_executions(id) ON DELETE CASCADE,
  activity_type VARCHAR(50) NOT NULL,
  activity_name VARCHAR(255) NOT NULL,
  status VARCHAR(20) NOT NULL CHECK(status IN ('started', 'completed', 'failed')),
  started_at TIMESTAMP DEFAULT NOW(),
  completed_at TIMESTAMP,
  duration_seconds INT,
  input_data JSONB,
  output_data JSONB,
  error_message TEXT,
  retry_attempt INT DEFAULT 1
);

CREATE INDEX idx_workflow_activities_workflow_execution_id ON workflow_activities(workflow_execution_id);
CREATE INDEX idx_workflow_activities_started_at ON workflow_activities(started_at);
```

#### Table: `users`
```sql
CREATE TABLE users (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  workos_id VARCHAR(255) UNIQUE NOT NULL,
  email VARCHAR(255) UNIQUE NOT NULL,
  name VARCHAR(255),
  avatar_url TEXT,
  role VARCHAR(50) DEFAULT 'developer' CHECK(role IN ('developer', 'admin', 'viewer')),
  is_active BOOLEAN DEFAULT TRUE,
  last_login_at TIMESTAMP,
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW()
);

CREATE INDEX idx_users_workos_id ON users(workos_id);
CREATE INDEX idx_users_email ON users(email);
```

### Acceptance Criteria
- [ ] All tables designed with proper constraints
- [ ] Foreign key relationships established
- [ ] Indexes created for query optimization
- [ ] Database migration files created (Alembic)
- [ ] Schema documented with ERD diagram
- [ ] Migration successfully applies to clean database
- [ ] All tables have proper audit fields (created_at, updated_at)

### Technical Tasks
1. Design complete database schema
2. Create Alembic migration file
3. Add proper indexes for performance
4. Document foreign key relationships
5. Create ERD diagram (using dbdiagram.io or similar)
6. Test migration on local PostgreSQL
7. Document schema in README

### Dependencies
- **Blocks**: "Set Up FastAPI Backend with PostgreSQL Support"

### Estimated Effort
**5 Story Points** (~3-4 hours)

### Labels
`database`, `schema`, `documentation`
""",
                "labels": ["database", "schema", "documentation"],
                "story_points": 5
            },
            {
                "title": "Implement WorkOS AuthKit Integration",
                "description": """## Task: Implement WorkOS AuthKit Integration

### Objective
Integrate WorkOS AuthKit for SSO authentication limited to heyarchie.ai domain users.

### Scope
- Set up WorkOS account and organization
- Configure heyarchie.ai SSO connection
- Implement frontend authentication UI
- Implement backend JWT validation
- Create protected route middleware
- Set up user session management

### WorkOS Configuration
1. Create WorkOS account
2. Set up organization for heyarchie.ai
3. Configure SSO connection (Google Workspace)
4. Get API keys and Client ID
5. Configure allowed redirect URIs

### Frontend Implementation
- Install `@workos-inc/authkit-nextjs`
- Create sign-in page
- Create authentication callback handler
- Implement protected route wrapper
- Add sign-out functionality
- Display user profile information

### Backend Implementation
- Install `workos` Python SDK
- Implement JWT validation middleware
- Create user session endpoint
- Sync WorkOS users to database
- Implement role-based access control

### Authentication Flow
```
1. User visits protected page → Redirect to WorkOS
2. WorkOS authenticates via heyarchie.ai SSO
3. WorkOS redirects back with authorization code
4. Frontend exchanges code for JWT token
5. Backend validates JWT and creates session
6. User synced to database (if new)
7. Session maintained via secure cookies
```

### Acceptance Criteria
- [ ] WorkOS account configured for heyarchie.ai
- [ ] SSO connection working for heyarchie.ai users
- [ ] Frontend sign-in flow functional
- [ ] Backend validates JWT tokens correctly
- [ ] Users synced to `users` table on first login
- [ ] Protected routes require authentication
- [ ] Sign-out functionality works
- [ ] User profile displayed in UI
- [ ] Session persists across page refreshes
- [ ] Non-heyarchie.ai users cannot authenticate

### Technical Tasks
1. Set up WorkOS account and organization
2. Configure heyarchie.ai SSO (Google Workspace)
3. Install WorkOS SDKs (frontend + backend)
4. Implement frontend authentication pages
5. Create authentication callback handler
6. Implement backend JWT validation middleware
7. Create user sync logic (WorkOS → PostgreSQL)
8. Add protected route wrapper
9. Test complete authentication flow
10. Document authentication setup

### Environment Variables
```
# Frontend
NEXT_PUBLIC_WORKOS_CLIENT_ID=client_xxx
WORKOS_API_KEY=sk_xxx
WORKOS_REDIRECT_URI=https://archie.build/auth/callback

# Backend
WORKOS_API_KEY=sk_xxx
WORKOS_CLIENT_ID=client_xxx
```

### Dependencies
- **Blocks**: "Set Up Next.js 14+ Frontend with TypeScript and Shadcn/ui"
- **Blocks**: "Design PostgreSQL Database Schema"

### Estimated Effort
**8 Story Points** (~5-6 hours)

### Labels
`authentication`, `frontend`, `backend`, `security`
""",
                "labels": ["authentication", "frontend", "backend", "security"],
                "story_points": 8
            },
            {
                "title": "Configure Railway Deployment",
                "description": """## Task: Configure Railway Deployment

### Objective
Set up Railway deployment for backend, frontend, and PostgreSQL database with proper environment configuration.

### Scope
- Create Railway account and project
- Deploy PostgreSQL database
- Configure backend service deployment
- Configure frontend service deployment
- Set up environment variables
- Configure custom domains
- Set up deployment pipelines

### Railway Services

#### 1. PostgreSQL Database
- Create PostgreSQL 16 service
- Note connection details (host, port, user, password, database)
- Enable public access for migrations (optional)
- Configure connection pooling

#### 2. Backend Service
- Connect GitHub repository
- Configure Python runtime (3.11+)
- Set build command: `cd backend && pip install -r requirements.txt`
- Set start command: `cd backend && uvicorn app.main:app --host 0.0.0.0 --port $PORT`
- Configure environment variables
- Set health check path: `/api/health`
- Configure auto-deploy on push to main

#### 3. Frontend Service
- Connect GitHub repository
- Configure Node.js runtime
- Set build command: `cd frontend && npm install && npm run build`
- Set start command: `cd frontend && npm start`
- Configure environment variables
- Set health check path: `/`
- Configure auto-deploy on push to main

### Environment Variables

**Backend:**
```
DATABASE_URL=${{Postgres.DATABASE_URL}}
WORKOS_API_KEY=sk_xxx
WORKOS_CLIENT_ID=client_xxx
LOG_LEVEL=INFO
PORT=8000
```

**Frontend:**
```
NEXT_PUBLIC_API_URL=${{Backend.RAILWAY_PUBLIC_DOMAIN}}
NEXT_PUBLIC_WORKOS_CLIENT_ID=client_xxx
WORKOS_API_KEY=sk_xxx
WORKOS_REDIRECT_URI=${{Frontend.RAILWAY_PUBLIC_DOMAIN}}/auth/callback
NODE_ENV=production
```

### Custom Domains
- Backend: `api.archie.build`
- Frontend: `archie.build`
- Configure DNS records (CNAME to Railway)
- Enable automatic SSL certificates

### Acceptance Criteria
- [ ] Railway project created
- [ ] PostgreSQL database deployed and accessible
- [ ] Backend service deployed successfully
- [ ] Frontend service deployed successfully
- [ ] All environment variables configured
- [ ] Custom domains configured (if available)
- [ ] Health checks passing for all services
- [ ] Auto-deploy enabled for main branch
- [ ] Database migrations run successfully on deployment
- [ ] Services can communicate (frontend → backend → database)

### Technical Tasks
1. Create Railway account
2. Create new project: "archie-dev"
3. Deploy PostgreSQL service
4. Configure backend service from GitHub
5. Configure frontend service from GitHub
6. Set environment variables for all services
7. Test deployment process
8. Configure custom domains (optional)
9. Set up monitoring and logs
10. Document deployment process

### Cost Estimate
- PostgreSQL: ~$5/month
- Backend: ~$5/month
- Frontend: ~$5/month
- **Total: ~$15-20/month**

### Dependencies
- **Blocks**: "Set Up FastAPI Backend with PostgreSQL Support"
- **Blocks**: "Set Up Next.js 14+ Frontend with TypeScript and Shadcn/ui"
- **Blocks**: "Design PostgreSQL Database Schema"

### Estimated Effort
**5 Story Points** (~3-4 hours)

### Labels
`deployment`, `devops`, `infrastructure`
""",
                "labels": ["deployment", "devops", "infrastructure"],
                "story_points": 5
            },
            {
                "title": "Set Up CI/CD Pipeline with GitHub Actions",
                "description": """## Task: Set Up CI/CD Pipeline

### Objective
Configure GitHub Actions workflows for automated testing, linting, and deployment validation.

### Scope
- Create CI workflow for backend (tests, linting)
- Create CI workflow for frontend (tests, linting, type checking)
- Create deployment validation workflow
- Configure automated checks for pull requests
- Set up status badges

### Workflows to Create

#### 1. Backend CI Workflow (`.github/workflows/backend-ci.yml`)
```yaml
name: Backend CI

on:
  push:
    branches: [main, develop]
    paths:
      - 'backend/**'
      - '.github/workflows/backend-ci.yml'
  pull_request:
    paths:
      - 'backend/**'

jobs:
  test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:16
        env:
          POSTGRES_PASSWORD: postgres
          POSTGRES_DB: test_db
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
      - name: Install dependencies
        run: cd backend && pip install -r requirements.txt && pip install pytest pytest-cov pytest-asyncio
      - name: Run tests
        run: cd backend && pytest --cov=app --cov-report=xml
        env:
          DATABASE_URL: postgresql+asyncpg://postgres:postgres@localhost:5432/test_db
      - name: Upload coverage
        uses: codecov/codecov-action@v3
        with:
          files: ./backend/coverage.xml

  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
      - name: Install dependencies
        run: pip install ruff black mypy
      - name: Run linters
        run: |
          cd backend
          ruff check .
          black --check .
          mypy app/
```

#### 2. Frontend CI Workflow (`.github/workflows/frontend-ci.yml`)
```yaml
name: Frontend CI

on:
  push:
    branches: [main, develop]
    paths:
      - 'frontend/**'
      - '.github/workflows/frontend-ci.yml'
  pull_request:
    paths:
      - 'frontend/**'

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
          cache-dependency-path: frontend/package-lock.json
      - name: Install dependencies
        run: cd frontend && npm ci
      - name: Type check
        run: cd frontend && npm run type-check
      - name: Lint
        run: cd frontend && npm run lint
      - name: Run tests
        run: cd frontend && npm test
      - name: Build
        run: cd frontend && npm run build
```

#### 3. Deployment Validation Workflow (`.github/workflows/deploy-check.yml`)
```yaml
name: Deployment Validation

on:
  deployment_status:

jobs:
  validate:
    if: github.event.deployment_status.state == 'success'
    runs-on: ubuntu-latest
    steps:
      - name: Check backend health
        run: |
          curl -f https://api.archie.build/api/health || exit 1
      - name: Check frontend
        run: |
          curl -f https://archie.build || exit 1
```

### Acceptance Criteria
- [ ] Backend CI workflow runs on PR and push
- [ ] Frontend CI workflow runs on PR and push
- [ ] All tests pass in CI environment
- [ ] Linting checks pass
- [ ] Type checking passes (frontend)
- [ ] Test coverage uploaded to Codecov
- [ ] Deployment validation checks work
- [ ] Status badges added to README
- [ ] Branch protection rules configured (require CI pass)

### Technical Tasks
1. Create `.github/workflows/` directory
2. Create backend CI workflow file
3. Create frontend CI workflow file
4. Create deployment validation workflow
5. Configure PostgreSQL service for backend tests
6. Set up Codecov integration
7. Test workflows on feature branch
8. Configure branch protection rules
9. Add status badges to README

### Branch Protection Rules
- Require status checks to pass before merging
- Require PR review before merging
- Require linear history
- Do not allow bypassing required checks

### Dependencies
- **Blocks**: "Set Up FastAPI Backend with PostgreSQL Support"
- **Blocks**: "Set Up Next.js 14+ Frontend with TypeScript and Shadcn/ui"

### Estimated Effort
**5 Story Points** (~3-4 hours)

### Labels
`ci-cd`, `github-actions`, `testing`, `devops`
""",
                "labels": ["ci-cd", "github-actions", "testing", "devops"],
                "story_points": 5
            }
        ]
    },
    # EPIC 2 and subsequent EPICs would follow here...
    # Due to character limits, I'll create a separate message for remaining EPICs
]


def run_gh_command(args: List[str]) -> dict:
    """Run gh CLI command and return JSON result."""
    try:
        result = subprocess.run(
            ["gh"] + args,
            capture_output=True,
            text=True,
            check=True
        )
        if result.stdout:
            try:
                return json.loads(result.stdout)
            except json.JSONDecodeError:
                return {"output": result.stdout}
        return {"success": True}
    except subprocess.CalledProcessError as e:
        print(f"Error running gh command: {e.stderr}", file=sys.stderr)
        return {"error": e.stderr}


def create_project() -> str:
    """Create GitHub project and return project ID."""
    print(f"Creating GitHub project: {PROJECT_TITLE}")

    # Create project using gh CLI
    result = run_gh_command([
        "project", "create",
        "--owner", GITHUB_ORG,
        "--title", PROJECT_TITLE,
        "--format", "json"
    ])

    if "error" in result:
        print(f"Failed to create project: {result['error']}")
        sys.exit(1)

    project_url = result.get("url", "")
    project_number = project_url.split("/")[-1] if project_url else None

    print(f"✅ Project created: {project_url}")
    return project_number


def create_issue(title: str, body: str, labels: List[str]) -> int:
    """Create GitHub issue and return issue number."""
    print(f"  Creating issue: {title}")

    # Prepare labels
    label_args = []
    for label in labels:
        label_args.extend(["--label", label])

    result = run_gh_command([
        "issue", "create",
        "--repo", f"{GITHUB_ORG}/{GITHUB_REPO}",
        "--title", title,
        "--body", body,
        *label_args,
        "--json", "number"
    ])

    if "error" in result:
        print(f"    ❌ Failed to create issue: {result['error']}")
        return None

    issue_number = result.get("number")
    print(f"    ✅ Issue #{issue_number} created")

    time.sleep(0.5)  # Rate limiting
    return issue_number


def add_issue_to_project(project_number: str, issue_number: int):
    """Add issue to project."""
    print(f"    Adding issue #{issue_number} to project")

    result = run_gh_command([
        "project", "item-add", project_number,
        "--owner", GITHUB_ORG,
        "--url", f"https://github.com/{GITHUB_ORG}/{GITHUB_REPO}/issues/{issue_number}"
    ])

    if "error" in result:
        print(f"      ⚠️  Failed to add to project: {result['error']}")
    else:
        print(f"      ✅ Added to project")


def main():
    """Main execution function."""
    print("=" * 80)
    print("Creating GitHub Project for archie-dev v2")
    print("=" * 80)
    print()

    # Step 1: Create project
    project_number = create_project()
    print()

    # Step 2: Create EPICs and sub-issues
    epic_numbers = {}

    for epic in EPICS:
        print(f"\n📦 Creating EPIC: {epic['title']}")
        print("-" * 80)

        # Create EPIC issue
        epic_body = epic['description'] + f"\n\n## Story Points\n**{epic['story_points']} points**"
        epic_number = create_issue(
            title=epic['title'],
            body=epic_body,
            labels=epic['labels']
        )

        if epic_number:
            epic_numbers[epic['title']] = epic_number
            add_issue_to_project(project_number, epic_number)

            # Create sub-issues
            print(f"\n  Creating {len(epic['sub_issues'])} sub-issues...")
            for sub_issue in epic['sub_issues']:
                # Add reference to parent EPIC in sub-issue body
                sub_issue_body = sub_issue['description']
                sub_issue_body += f"\n\n---\n**Parent EPIC:** #{epic_number} {epic['title']}"
                sub_issue_body += f"\n**Story Points:** {sub_issue['story_points']}"

                sub_number = create_issue(
                    title=sub_issue['title'],
                    body=sub_issue_body,
                    labels=sub_issue['labels']
                )

                if sub_number:
                    add_issue_to_project(project_number, sub_number)

        print()

    # Summary
    print("\n" + "=" * 80)
    print("✅ GitHub Project Creation Complete!")
    print("=" * 80)
    print(f"\nProject: https://github.com/orgs/{GITHUB_ORG}/projects/{project_number}")
    print(f"\nEPICs Created:")
    for epic_title, epic_number in epic_numbers.items():
        print(f"  - {epic_title}: #{epic_number}")
    print(f"\nTotal Issues Created: {len(epic_numbers) + sum(len(e['sub_issues']) for e in EPICS)}")
    print()


if __name__ == "__main__":
    main()
