name: CI

on:
  push:
    branches: [main]
  pull_request:

jobs:
  backend:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:16-alpine
        env:
          POSTGRES_USER: writer
          POSTGRES_PASSWORD: writer
          POSTGRES_DB: writer
        ports: ["5432:5432"]
        options: >-
          --health-cmd "pg_isready -U writer"
          --health-interval 5s --health-timeout 3s --health-retries 10
    env:
      DATABASE_URL: postgresql+asyncpg://writer:writer@localhost:5432/writer
      DATABASE_URL_SYNC: postgresql+psycopg://writer:writer@localhost:5432/writer
    steps:
      - uses: actions/checkout@v4
      - uses: astral-sh/setup-uv@v5
      - run: uv sync
      - name: ruff
        run: uv run ruff check .
      - name: mypy
        run: uv run mypy packages apps
      - name: alembic upgrade + drift check
        run: |
          uv run alembic upgrade head
          uv run alembic check
      - name: pytest + coverage gate (>=80%)
        run: uv run pytest -q --cov --cov-report=term-missing --cov-fail-under=80

  # 打包冒烟：构建 ww-agents wheel → 装进裸 venv → import ww_agents 并断言 SPECS。
  # 证明 prompts/*.md 随 wheel 分发（源码树 pytest 测不出此漏带——见
  # docs/design/prompt-management.md §4/§6#16）。load_prompt 在 import 期读盘，
  # 若 .md 漏带则抛 PromptNotFoundError，本步即红。
  agents-wheel-smoke:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: astral-sh/setup-uv@v5
      - name: build ww-agents wheel
        run: uv build --wheel packages/agents --out-dir dist
      - name: install into bare venv + import SPECS
        run: |
          uv venv .smoke-venv
          # 工作区兄弟包按路径装（解析其第三方依赖）；structlog 是 ww-llm-gateway
          # import 期用到但未显式声明的传递依赖，显式补上以保证裸装可 import。
          uv pip install --python .smoke-venv \
            "ww-shared @ ./packages/shared" \
            "ww-config @ ./packages/config" \
            "ww-db @ ./packages/db" \
            "ww-llm-gateway @ ./packages/llm_gateway" \
            structlog
          # 被测产物：装 wheel 本身，--no-deps 确保 import 的是它而非源码树。
          uv pip install --python .smoke-venv --no-deps dist/ww_agents-*.whl
          .smoke-venv/bin/python -c "import ww_agents; assert ww_agents.SPECS"

  frontend:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: astral-sh/setup-uv@v5
      - run: uv sync
      - uses: actions/setup-node@v4
        with:
          node-version: 22
      - run: corepack enable
      - name: install
        working-directory: apps/web
        run: pnpm install --frozen-lockfile
      - name: gen api types
        working-directory: apps/web
        run: pnpm gen:api
      - name: lint
        working-directory: apps/web
        run: pnpm lint
      - name: typecheck
        working-directory: apps/web
        run: pnpm typecheck
      - name: test + coverage gate (>=80%)
        working-directory: apps/web
        run: pnpm test:coverage
