#!/usr/bin/env bash
# Batch 4: Issues #128-#142 for LLMHosts.com
set -euo pipefail
REPO="LookNoHandsMom/LLMHosts.com"

echo "=== Batch 4: Creating 15 issues ==="

echo "[1/15] Creating: Cost visualization charts..."
gh issue create --repo "$REPO" \
  --title "feat(dashboard): add interactive cost visualization charts" \
  --label "enhancement" \
  --body "## Description
Add interactive cost visualization charts to the web dashboard that display spending trends over time, cost breakdown by model/provider, and projected monthly costs based on current usage patterns. Users need clear visibility into how much they are saving by routing requests through local models versus cloud APIs.

## Acceptance Criteria
- [ ] Line chart showing daily/weekly/monthly cost trends with toggle
- [ ] Pie chart breaking down costs by model and provider
- [ ] Savings calculator comparing local vs cloud-only costs
- [ ] Charts use Recharts and match the existing dashboard theme
- [ ] Data sourced from the existing metrics/collector.py cost tracking"
sleep 3

echo "[2/15] Creating: Model usage analytics..."
gh issue create --repo "$REPO" \
  --title "feat(dashboard): model usage analytics with request volume heatmaps" \
  --label "enhancement" \
  --body "## Description
Implement a model usage analytics page in the web dashboard that shows request volume heatmaps by hour/day, latency percentiles per model, token throughput rates, and cache hit ratios. This gives operators insight into traffic patterns and helps them decide which models to keep loaded.

## Acceptance Criteria
- [ ] Heatmap visualization of request volume by hour-of-day and day-of-week
- [ ] Per-model latency histogram (p50, p95, p99)
- [ ] Token throughput graph (tokens/sec over time)
- [ ] Cache hit/miss ratio display per cache tier (exact, namespace, vCache)
- [ ] Filterable by date range and model name"
sleep 3

echo "[3/15] Creating: API key management UI..."
gh issue create --repo "$REPO" \
  --title "feat(dashboard): API key management UI with CRUD and usage stats" \
  --label "enhancement,security" \
  --body "## Description
Build an API key management interface in the web dashboard that allows users to create, view, revoke, and rotate API keys without using the CLI. Each key should display its associated plan tier, rate limit status, and recent usage statistics. This complements the existing /api/keys/* REST endpoints.

## Acceptance Criteria
- [ ] Table view listing all API keys with masked display (show last 4 chars)
- [ ] Create new key with name, plan tier selection, and optional expiry date
- [ ] Revoke and rotate actions with confirmation dialog
- [ ] Per-key usage stats (request count, last used timestamp, rate limit remaining)
- [ ] Copy-to-clipboard for newly created keys
- [ ] Responsive layout that works on tablet and desktop"
sleep 3

echo "[4/15] Creating: E2E proxy tests..."
gh issue create --repo "$REPO" \
  --title "test(e2e): end-to-end proxy tests with real Ollama backend" \
  --label "testing" \
  --body "## Description
Create a comprehensive end-to-end test suite that spins up a real Ollama instance (via Docker), starts the LLMHosts proxy, and validates the full request lifecycle through both OpenAI and Anthropic compatible endpoints. Current tests use ASGI transport with mocked backends; we need tests that verify the actual proxy-to-backend data flow.

## Acceptance Criteria
- [ ] Docker Compose test fixture that starts Ollama with a small model (e.g., tinyllama)
- [ ] E2E tests for /v1/chat/completions (OpenAI) and /v1/messages (Anthropic)
- [ ] Streaming and non-streaming response validation
- [ ] Verify response headers (X-Request-ID, X-LLMHosts-Cost, X-LLMHosts-Model)
- [ ] Tests marked with @pytest.mark.e2e and skipped in CI unless --run-e2e flag is set
- [ ] Cleanup teardown that removes containers after test run"
sleep 3

echo "[5/15] Creating: Load testing suite..."
gh issue create --repo "$REPO" \
  --title "test(performance): load testing suite with Locust for proxy endpoints" \
  --label "testing,performance" \
  --body "## Description
Implement a load testing suite using Locust that benchmarks the proxy under concurrent request load. The suite should measure throughput, latency percentiles, error rates, and resource consumption at various concurrency levels. This establishes baseline performance numbers and catches regressions.

## Acceptance Criteria
- [ ] Locust test file targeting /v1/chat/completions and /v1/models endpoints
- [ ] Configurable concurrency levels (10, 50, 100, 500 users)
- [ ] HTML report generation with latency percentiles and throughput graphs
- [ ] Baseline performance thresholds documented (e.g., p99 < 500ms for /v1/models)
- [ ] CI-compatible headless mode with pass/fail based on thresholds
- [ ] Instructions in tests/load/README.md for running locally"
sleep 3

echo "[6/15] Creating: Contract tests..."
gh issue create --repo "$REPO" \
  --title "test(contract): OpenAI and Anthropic API contract tests" \
  --label "testing" \
  --body "## Description
Add contract tests that validate LLMHosts proxy responses strictly conform to the OpenAI and Anthropic API specifications. These tests should catch schema drift when we update our proxy routes and ensure clients using official SDKs will not break. Use JSON Schema validation against the official API specs.

## Acceptance Criteria
- [ ] JSON Schema files for OpenAI chat completion response (streaming and non-streaming)
- [ ] JSON Schema files for Anthropic messages response (streaming and non-streaming)
- [ ] Contract tests validate every response field, type, and required/optional status
- [ ] Error response format contract tests (400, 401, 429, 500 codes)
- [ ] Tests marked with @pytest.mark.contract
- [ ] Schema files stored in tests/contracts/ for easy updates when upstream APIs change"
sleep 3

echo "[7/15] Creating: Kubernetes Helm chart..."
gh issue create --repo "$REPO" \
  --title "feat(infra): Kubernetes Helm chart for LLMHosts deployment" \
  --label "enhancement,help wanted" \
  --body "## Description
Create a Helm chart that deploys LLMHosts on Kubernetes clusters, supporting GPU node scheduling, horizontal pod autoscaling based on request queue depth, and persistent volume claims for cache and audit storage. This enables users running K3s or full Kubernetes to deploy LLMHosts alongside their existing infrastructure.

## Acceptance Criteria
- [ ] Helm chart in deploy/helm/llmhosts/ with standard structure (Chart.yaml, values.yaml, templates/)
- [ ] GPU node affinity and tolerations configurable via values.yaml
- [ ] HPA configuration based on custom metrics (request queue depth)
- [ ] PVC templates for cache storage and SQLite audit database
- [ ] ConfigMap for TOML configuration injection
- [ ] Secret resource for API keys and BYOK credentials
- [ ] README with installation instructions and common value overrides"
sleep 3

echo "[8/15] Creating: Docker Swarm support..."
gh issue create --repo "$REPO" \
  --title "feat(infra): Docker Swarm stack file for multi-node deployment" \
  --label "enhancement" \
  --body "## Description
Add a Docker Swarm stack file that enables multi-node LLMHosts deployment for users who prefer Swarm over Kubernetes. The stack should support GPU resource reservations, service replicas with rolling updates, and shared volume configuration for cache persistence across nodes.

## Acceptance Criteria
- [ ] deploy/swarm/docker-stack.yml with production-ready service definitions
- [ ] GPU resource reservation using Docker generic resources
- [ ] Rolling update configuration with health check-based deployment
- [ ] Overlay network for inter-node communication
- [ ] Shared NFS or similar volume mount for cache persistence
- [ ] Documentation in deploy/swarm/README.md with setup and scaling instructions"
sleep 3

echo "[9/15] Creating: systemd service unit..."
gh issue create --repo "$REPO" \
  --title "feat(infra): systemd service unit for bare-metal installation" \
  --label "enhancement,good first issue" \
  --body "## Description
Provide a systemd service unit file and installation script so users running LLMHosts on bare metal can manage it as a proper system service with automatic restart, logging to journald, and startup on boot. Many home GPU users run Linux directly without containers and need a reliable way to keep LLMHosts running.

## Acceptance Criteria
- [ ] deploy/systemd/llmhosts.service unit file with proper security directives (PrivateTmp, ProtectSystem)
- [ ] deploy/systemd/install.sh script that creates user, installs service, and enables it
- [ ] Automatic restart on failure with configurable backoff
- [ ] Environment file support for LLMHOST_* configuration variables
- [ ] llmhost doctor pre-start check as ExecStartPre directive
- [ ] Uninstall script that cleanly removes the service"
sleep 3

echo "[10/15] Creating: Onboarding wizard improvements..."
gh issue create --repo "$REPO" \
  --title "feat(onboarding): interactive setup wizard with hardware-aware recommendations" \
  --label "enhancement" \
  --body "## Description
Enhance the llmhost setup onboarding wizard to automatically detect GPU hardware, suggest optimal models based on available VRAM, configure the router tiers appropriately, and offer guided BYOK key setup. The current wizard handles basic configuration but does not leverage the hardware discovery module to make smart defaults.

## Acceptance Criteria
- [ ] Auto-detect GPU model and VRAM using existing discovery/hardware.py
- [ ] Suggest top 3 models that fit in available VRAM with download size estimates
- [ ] Configure router tier thresholds based on detected hardware capability
- [ ] Step-by-step BYOK key entry with provider validation (test API call)
- [ ] Summary screen showing configured backends, router settings, and tunnel status
- [ ] Option to export configuration as shareable TOML snippet"
sleep 3

echo "[11/15] Creating: Mobile responsive dashboard..."
gh issue create --repo "$REPO" \
  --title "feat(dashboard): mobile responsive layout for web dashboard" \
  --label "enhancement,good first issue" \
  --body "## Description
Make the web dashboard fully responsive for mobile and tablet viewports so users can monitor their LLMHosts instance from a phone while away from their desk. The current dashboard layout assumes desktop-width screens and becomes unusable below 768px. Key monitoring views (health status, request count, model status) should be accessible on mobile.

## Acceptance Criteria
- [ ] Responsive breakpoints at 640px (mobile), 768px (tablet), 1024px (desktop)
- [ ] Collapsible sidebar navigation with hamburger menu on mobile
- [ ] Stacked card layout for metrics on small screens
- [ ] Touch-friendly chart interactions (tap instead of hover for tooltips)
- [ ] Dashboard usable in both portrait and landscape orientation
- [ ] No horizontal scroll on any viewport width"
sleep 3

echo "[12/15] Creating: Dark/light theme toggle..."
gh issue create --repo "$REPO" \
  --title "feat(dashboard): dark and light theme toggle with system preference detection" \
  --label "enhancement,good first issue" \
  --body "## Description
Add a dark/light theme toggle to the web dashboard that respects the OS-level preference by default and allows manual override. The current dashboard uses a fixed dark theme. Both themes should maintain proper contrast ratios for accessibility (WCAG AA) and persist the choice across sessions via localStorage.

## Acceptance Criteria
- [ ] Theme toggle button in the dashboard header
- [ ] Default to OS preference via prefers-color-scheme media query
- [ ] Manual override persisted in localStorage
- [ ] Both themes pass WCAG AA contrast ratio requirements
- [ ] TailwindCSS dark mode classes used consistently (no inline color overrides)
- [ ] Charts and graphs adapt colors to current theme"
sleep 3

echo "[13/15] Creating: CI/CD pipeline..."
gh issue create --repo "$REPO" \
  --title "feat(ci): GitHub Actions CI/CD pipeline with test matrix and artifact publishing" \
  --label "enhancement" \
  --body "## Description
Implement a comprehensive GitHub Actions CI/CD pipeline that runs linting (ruff), type checking (mypy), the full pytest suite across Python 3.10-3.12, builds the wheel, and publishes to PyPI on tagged releases. The current project has no CI; all testing is manual. This is a prerequisite for reliable releases and contributor confidence.

## Acceptance Criteria
- [ ] .github/workflows/ci.yml with lint, typecheck, and test jobs
- [ ] Test matrix covering Python 3.10, 3.11, and 3.12 on Ubuntu
- [ ] Separate job for building and verifying the wheel artifact
- [ ] PyPI publish job triggered only on version tags (v*)
- [ ] Test results and coverage report uploaded as workflow artifacts
- [ ] Status badges added to README.md
- [ ] Workflow caching for pip dependencies to reduce CI time"
sleep 3

echo "[14/15] Creating: Automated release process..."
gh issue create --repo "$REPO" \
  --title "feat(ci): automated release process with changelog generation" \
  --label "enhancement" \
  --body "## Description
Create an automated release workflow that generates a changelog from conventional commits, bumps the version in llmhost/version.py, creates a GitHub Release with release notes, and triggers the PyPI publish pipeline. Currently releases require manual version bumping, changelog writing, and tag creation, which is error-prone and slow.

## Acceptance Criteria
- [ ] Release workflow triggered by workflow_dispatch with version bump type (patch/minor/major)
- [ ] Auto-generate changelog from conventional commit messages since last tag
- [ ] Bump version in llmhost/version.py and llmhost/__init__.py
- [ ] Create annotated git tag and GitHub Release with generated notes
- [ ] Trigger downstream CI/CD publish job for PyPI
- [ ] Dry-run mode that previews changelog without making changes"
sleep 3

echo "[15/15] Creating: Health check improvements..."
gh issue create --repo "$REPO" \
  --title "feat(health): deep health checks with dependency verification and self-healing" \
  --label "enhancement" \
  --body "## Description
Enhance the health monitoring system to perform deep health checks that verify not just backend availability but also GPU memory utilization, cache storage capacity, tunnel connectivity, and database integrity. Add self-healing capabilities that automatically restart failed backends, clear cache when storage is critically low, and re-establish dropped tunnel connections.

## Acceptance Criteria
- [ ] Deep health check endpoint at /health/deep that tests all subsystems
- [ ] GPU memory utilization check with configurable warning/critical thresholds
- [ ] Cache storage capacity monitoring with automatic eviction when above 90%
- [ ] Tunnel connectivity verification with automatic reconnection attempt
- [ ] SQLite audit database integrity check (PRAGMA integrity_check)
- [ ] Self-healing actions logged to audit trail with before/after status
- [ ] Health check results exposed as Prometheus metrics"

echo ""
echo "=== All 15 issues created successfully ==="
