"""Core schema: patterns, knowledge, work items, sessions, quality, documents.

These tables exist in every GreyMatter deployment (Solo and Distributed).
"""

SQLITE_DDL = """
CREATE TABLE IF NOT EXISTS patterns (
    id TEXT PRIMARY KEY,
    type TEXT NOT NULL,
    domain TEXT NOT NULL,
    title TEXT NOT NULL,
    observation TEXT NOT NULL,
    confidence TEXT DEFAULT 'low',
    confirmations INTEGER DEFAULT 0,
    applications INTEGER DEFAULT 0,
    last_applied_at TEXT,
    created_at TEXT DEFAULT (datetime('now')),
    updated_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS pattern_evidence (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    pattern_id TEXT NOT NULL REFERENCES patterns(id),
    session_id TEXT,
    work_item_id TEXT,
    outcome TEXT DEFAULT 'confirmed',
    created_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS knowledge_entries (
    id TEXT PRIMARY KEY,
    entry_type TEXT NOT NULL,
    scope TEXT DEFAULT 'cross-cutting',
    domain TEXT,
    title TEXT NOT NULL,
    content TEXT NOT NULL,
    valence TEXT,
    confidence REAL DEFAULT 0.5,
    applied_count INTEGER DEFAULT 0,
    tags TEXT,
    classification_level INTEGER NOT NULL DEFAULT 3,
    knowledge_category TEXT DEFAULT 'domain_expertise',
    ttl_days INTEGER DEFAULT 90,
    created_at TEXT DEFAULT (datetime('now')),
    updated_at TEXT DEFAULT (datetime('now')),
    pruned_at TEXT,
    stale_flagged_at TEXT,
    last_confirmed_at TEXT
);

CREATE TABLE IF NOT EXISTS work_items (
    id TEXT PRIMARY KEY,
    title TEXT NOT NULL,
    description TEXT,
    status TEXT DEFAULT 'queued',
    priority INTEGER DEFAULT 100,
    domain_tags TEXT,
    assigned_to TEXT,
    project TEXT DEFAULT 'greymatter',
    feature TEXT DEFAULT 'general',
    type TEXT DEFAULT 'task',
    short_id TEXT,
    review_notes TEXT,
    dispatch_mode TEXT,
    created_at TEXT DEFAULT (datetime('now')),
    completed_at TEXT
);

CREATE TABLE IF NOT EXISTS sessions (
    id TEXT PRIMARY KEY,
    started_at TEXT DEFAULT (datetime('now')),
    ended_at TEXT,
    project TEXT,
    patterns_applied TEXT,
    work_completed TEXT,
    summary TEXT,
    state TEXT DEFAULT 'active',
    active_work_item_id TEXT,
    checkpoint_at TEXT,
    compaction_count INTEGER DEFAULT 0,
    environment TEXT
);

CREATE TABLE IF NOT EXISTS session_checkpoints (
    id TEXT PRIMARY KEY,
    session_id TEXT NOT NULL,
    checkpoint_at TEXT NOT NULL,
    state TEXT NOT NULL,
    active_work_item_id TEXT,
    compaction_count INTEGER DEFAULT 0,
    context_summary TEXT,
    open_items TEXT,
    FOREIGN KEY (session_id) REFERENCES sessions(id)
);

CREATE TABLE IF NOT EXISTS llm_completions (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    timestamp TEXT DEFAULT (datetime('now')),
    provider TEXT NOT NULL,
    model TEXT NOT NULL,
    tokens_used INTEGER,
    cost_estimate REAL DEFAULT 0.0,
    task_type TEXT,
    latency_ms INTEGER
);

CREATE TABLE IF NOT EXISTS quality_standards (
    id TEXT PRIMARY KEY,
    category TEXT NOT NULL,
    rule TEXT NOT NULL,
    severity TEXT NOT NULL,
    example_good TEXT,
    example_bad TEXT,
    rationale TEXT,
    active INTEGER DEFAULT 1,
    created_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS build_runs (
    id TEXT PRIMARY KEY,
    session_id TEXT REFERENCES sessions(id),
    approach TEXT NOT NULL,
    task_name TEXT NOT NULL,
    started_at TEXT DEFAULT (datetime('now')),
    completed_at TEXT,
    lines_written INTEGER,
    test_count INTEGER,
    tests_passing INTEGER,
    first_pass_success INTEGER DEFAULT 0
);

CREATE TABLE IF NOT EXISTS quality_scores (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    build_run_id TEXT NOT NULL REFERENCES build_runs(id),
    standard_id TEXT NOT NULL REFERENCES quality_standards(id),
    passed INTEGER NOT NULL,
    detail TEXT,
    found_by TEXT,
    found_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS review_issues (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    build_run_id TEXT NOT NULL REFERENCES build_runs(id),
    severity TEXT NOT NULL,
    category TEXT NOT NULL,
    description TEXT NOT NULL,
    fixed_at TEXT,
    time_to_fix_minutes INTEGER,
    found_by TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS documents (
    id TEXT PRIMARY KEY,
    doc_type TEXT NOT NULL,
    title TEXT NOT NULL,
    content TEXT NOT NULL,
    format TEXT DEFAULT 'markdown',
    tags TEXT,
    project TEXT,
    parent_id TEXT,
    summary TEXT,
    token_estimate INTEGER,
    created_at TEXT DEFAULT (datetime('now')),
    updated_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS context_requests (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    session_id TEXT,
    query TEXT NOT NULL,
    documents_served TEXT,
    tokens_served INTEGER,
    relevance_score REAL,
    requested_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS embedding_chunks (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    source_table TEXT NOT NULL,
    source_id TEXT NOT NULL,
    chunk_index INTEGER NOT NULL,
    chunk_text TEXT NOT NULL,
    created_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS corrections (
    id TEXT PRIMARY KEY,
    domain TEXT NOT NULL,
    trigger_text TEXT NOT NULL,
    correction_text TEXT NOT NULL,
    context TEXT,
    source TEXT DEFAULT 'user',
    session_id TEXT NOT NULL,
    work_item_id TEXT,
    applications INTEGER DEFAULT 0,
    created_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS soul_index (
    section TEXT PRIMARY KEY,
    content TEXT,
    updated_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS drift_warnings (
    id TEXT PRIMARY KEY,
    domain TEXT NOT NULL,
    drift_level TEXT NOT NULL,
    invalid_count INTEGER DEFAULT 0,
    created_at TEXT DEFAULT (datetime('now')),
    acknowledged_at TEXT,
    acknowledged_by TEXT
);

CREATE TABLE IF NOT EXISTS session_states (
    id TEXT PRIMARY KEY,
    session_id TEXT NOT NULL,
    compaction_number INTEGER NOT NULL,
    state_version INTEGER NOT NULL DEFAULT 1,
    state_data TEXT NOT NULL,
    captured_at TEXT DEFAULT (datetime('now')),
    FOREIGN KEY (session_id) REFERENCES sessions(id)
);

CREATE INDEX IF NOT EXISTS idx_session_states_session
    ON session_states(session_id, compaction_number DESC);

CREATE TABLE IF NOT EXISTS _schema_metadata (
    key TEXT PRIMARY KEY,
    value TEXT,
    updated_at TEXT DEFAULT (datetime('now'))
);
"""

CRDB_DDL = """
CREATE TABLE IF NOT EXISTS patterns (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    type TEXT NOT NULL,
    domain TEXT NOT NULL,
    title TEXT NOT NULL,
    observation TEXT NOT NULL,
    confidence TEXT DEFAULT 'low',
    confirmations INT DEFAULT 0,
    applications INT DEFAULT 0,
    last_applied_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ DEFAULT now(),
    updated_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS pattern_evidence (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    pattern_id UUID NOT NULL,
    session_id UUID,
    work_item_id UUID,
    outcome TEXT DEFAULT 'confirmed',
    created_at TIMESTAMPTZ DEFAULT now(),
    CONSTRAINT fk_pattern_evidence_pattern
        FOREIGN KEY (pattern_id) REFERENCES patterns(id)
);

CREATE TABLE IF NOT EXISTS knowledge_entries (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    entry_type TEXT NOT NULL,
    scope TEXT DEFAULT 'cross-cutting',
    domain TEXT,
    title TEXT NOT NULL,
    content TEXT NOT NULL,
    valence TEXT,
    confidence DECIMAL(5,4) DEFAULT 0.5,
    applied_count INT DEFAULT 0,
    tags TEXT,
    classification_level INT NOT NULL DEFAULT 3,
    knowledge_category TEXT DEFAULT 'domain_expertise',
    ttl_days INT DEFAULT 90,
    created_at TIMESTAMPTZ DEFAULT now(),
    updated_at TIMESTAMPTZ DEFAULT now(),
    pruned_at TIMESTAMPTZ
);

CREATE TABLE IF NOT EXISTS work_items (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    title TEXT NOT NULL,
    description TEXT,
    status TEXT DEFAULT 'queued',
    priority INT DEFAULT 100,
    domain_tags TEXT,
    assigned_to TEXT,
    project TEXT DEFAULT 'greymatter',
    feature TEXT DEFAULT 'general',
    type TEXT DEFAULT 'task',
    short_id TEXT,
    review_notes TEXT,
    dispatch_mode TEXT,
    created_at TIMESTAMPTZ DEFAULT now(),
    completed_at TIMESTAMPTZ
);

CREATE TABLE IF NOT EXISTS sessions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    started_at TIMESTAMPTZ DEFAULT now(),
    ended_at TIMESTAMPTZ,
    project TEXT,
    patterns_applied TEXT,
    work_completed TEXT,
    summary TEXT,
    state TEXT DEFAULT 'active',
    active_work_item_id TEXT,
    checkpoint_at TIMESTAMPTZ,
    compaction_count INT DEFAULT 0,
    environment TEXT
);

CREATE TABLE IF NOT EXISTS session_checkpoints (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    session_id UUID NOT NULL,
    checkpoint_at TIMESTAMPTZ NOT NULL,
    state TEXT NOT NULL,
    active_work_item_id TEXT,
    compaction_count INT DEFAULT 0,
    context_summary TEXT,
    open_items TEXT,
    CONSTRAINT fk_session_checkpoints_session
        FOREIGN KEY (session_id) REFERENCES sessions(id)
);

CREATE TABLE IF NOT EXISTS llm_completions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    timestamp TIMESTAMPTZ DEFAULT now(),
    provider TEXT NOT NULL,
    model TEXT NOT NULL,
    tokens_used INT,
    cost_estimate DECIMAL(12,6) DEFAULT 0.0,
    task_type TEXT,
    latency_ms INT
);

CREATE TABLE IF NOT EXISTS quality_standards (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    category TEXT NOT NULL,
    rule TEXT NOT NULL,
    severity TEXT NOT NULL,
    example_good TEXT,
    example_bad TEXT,
    rationale TEXT,
    active INT DEFAULT 1,
    created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS build_runs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    session_id UUID REFERENCES sessions(id),
    approach TEXT NOT NULL,
    task_name TEXT NOT NULL,
    started_at TIMESTAMPTZ DEFAULT now(),
    completed_at TIMESTAMPTZ,
    lines_written INT,
    test_count INT,
    tests_passing INT,
    first_pass_success INT DEFAULT 0
);

CREATE TABLE IF NOT EXISTS quality_scores (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    build_run_id UUID NOT NULL REFERENCES build_runs(id),
    standard_id UUID NOT NULL REFERENCES quality_standards(id),
    passed INT NOT NULL,
    detail TEXT,
    found_by TEXT,
    found_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS review_issues (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    build_run_id UUID NOT NULL REFERENCES build_runs(id),
    severity TEXT NOT NULL,
    category TEXT NOT NULL,
    description TEXT NOT NULL,
    fixed_at TIMESTAMPTZ,
    time_to_fix_minutes INT,
    found_by TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS documents (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    doc_type TEXT NOT NULL,
    title TEXT NOT NULL,
    content TEXT NOT NULL,
    format TEXT DEFAULT 'markdown',
    tags TEXT,
    project TEXT,
    parent_id TEXT,
    summary TEXT,
    token_estimate INT,
    created_at TIMESTAMPTZ DEFAULT now(),
    updated_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS context_requests (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    session_id TEXT,
    query TEXT NOT NULL,
    documents_served TEXT,
    tokens_served INT,
    relevance_score DECIMAL(5,4),
    requested_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS embedding_chunks (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    source_table TEXT NOT NULL,
    source_id TEXT NOT NULL,
    chunk_index INT NOT NULL,
    chunk_text TEXT NOT NULL,
    created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS corrections (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    domain TEXT NOT NULL,
    trigger_text TEXT NOT NULL,
    correction_text TEXT NOT NULL,
    context TEXT,
    source TEXT DEFAULT 'user',
    session_id TEXT NOT NULL,
    work_item_id UUID,
    applications INT DEFAULT 0,
    created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS soul_index (
    section TEXT PRIMARY KEY,
    content TEXT,
    updated_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS drift_warnings (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    domain TEXT NOT NULL,
    drift_level TEXT NOT NULL,
    invalid_count INT DEFAULT 0,
    created_at TIMESTAMPTZ DEFAULT now(),
    acknowledged_at TIMESTAMPTZ,
    acknowledged_by TEXT
);

CREATE TABLE IF NOT EXISTS session_states (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    session_id UUID NOT NULL,
    compaction_number INT NOT NULL,
    state_version INT NOT NULL DEFAULT 1,
    state_data JSONB NOT NULL,
    captured_at TIMESTAMPTZ DEFAULT now(),
    CONSTRAINT fk_session_states_session
        FOREIGN KEY (session_id) REFERENCES sessions(id)
);

CREATE INDEX IF NOT EXISTS idx_session_states_session
    ON session_states(session_id, compaction_number DESC);

CREATE TABLE IF NOT EXISTS _schema_metadata (
    key TEXT PRIMARY KEY,
    value TEXT,
    updated_at TIMESTAMPTZ DEFAULT now()
);

-- Core indexes
CREATE INDEX IF NOT EXISTS idx_sessions_started ON sessions(started_at);
CREATE INDEX IF NOT EXISTS idx_patterns_domain ON patterns(domain);
CREATE INDEX IF NOT EXISTS idx_patterns_confidence ON patterns(confidence);
CREATE INDEX IF NOT EXISTS idx_pattern_evidence_pattern ON pattern_evidence(pattern_id);
CREATE INDEX IF NOT EXISTS idx_corrections_domain ON corrections(domain);
CREATE INDEX IF NOT EXISTS idx_drift_warnings_domain ON drift_warnings(domain);
CREATE INDEX IF NOT EXISTS idx_work_items_project ON work_items(project);
CREATE INDEX IF NOT EXISTS idx_work_items_status ON work_items(status);
"""


def get_sqlite_ddl() -> str:
    return SQLITE_DDL


def get_crdb_ddl() -> str:
    return CRDB_DDL
