-- Migration 003: Create prompt runs and manifests tables
-- Implements FR-4: PromptRun Lifecycle and FR-5: RunManifest Persistence
-- Date: 2026-02-08

-- Prompt runs table
CREATE TABLE IF NOT EXISTS prompt_runs (
    id TEXT PRIMARY KEY,
    template_id TEXT NOT NULL REFERENCES prompt_artifacts(id),
    input_bundle_hash TEXT NOT NULL,
    status TEXT NOT NULL,
    stage TEXT NOT NULL,
    parent_run_id TEXT REFERENCES prompt_runs(id),
    depth INTEGER DEFAULT 0,
    config JSON,
    started_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    completed_at TIMESTAMP,
    error_message TEXT,
    metadata JSON
);

-- Run manifests table
CREATE TABLE IF NOT EXISTS run_manifests (
    run_id TEXT PRIMARY KEY REFERENCES prompt_runs(id),
    template_metadata JSON NOT NULL,
    resolved_inputs JSON NOT NULL,
    compiled_prompt_digest TEXT NOT NULL,
    model_config JSON NOT NULL,
    output_artifacts JSON,
    dependency_edges JSON,
    validation_results JSON,
    impact_debt JSON,
    timing_metadata JSON,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Indexes for performance
CREATE INDEX IF NOT EXISTS idx_runs_template ON prompt_runs(template_id);
CREATE INDEX IF NOT EXISTS idx_runs_bundle_hash ON prompt_runs(input_bundle_hash);
CREATE INDEX IF NOT EXISTS idx_runs_parent ON prompt_runs(parent_run_id);
CREATE INDEX IF NOT EXISTS idx_runs_status ON prompt_runs(status);

-- Unique constraint for idempotency (FR-4.4)
-- Note: Allows multiple failed runs, but only one successful run per hash
CREATE UNIQUE INDEX IF NOT EXISTS idx_runs_successful_hash
    ON prompt_runs(input_bundle_hash)
    WHERE status = 'success';

-- Comments (for documentation)
-- prompt_runs.id: Unique UUID for this run
-- prompt_runs.template_id: Template being executed
-- prompt_runs.input_bundle_hash: SHA-256 hash for idempotency
-- prompt_runs.status: pending, running, success, failed, skipped
-- prompt_runs.stage: pending, analysis, compilation, processing, complete, failed
-- prompt_runs.parent_run_id: Parent run for nested generators
-- prompt_runs.depth: Nesting depth (0 for top-level)
-- prompt_runs.config: RunConfig JSON
-- prompt_runs.started_at: Execution start time
-- prompt_runs.completed_at: Execution completion time
-- prompt_runs.error_message: Error message if failed
-- prompt_runs.metadata: Additional metadata

-- run_manifests.run_id: Associated run ID
-- run_manifests.template_metadata: Template info (id, name, digest)
-- run_manifests.resolved_inputs: Array of resolved input artifacts
-- run_manifests.compiled_prompt_digest: Digest of compiled prompt
-- run_manifests.model_config: Model configuration used
-- run_manifests.output_artifacts: Array of produced artifacts
-- run_manifests.dependency_edges: Dependency graph edges
-- run_manifests.validation_results: Quality validation results
-- run_manifests.impact_debt: Suppressed recomputation records
-- run_manifests.timing_metadata: Stage timing information
