-- Knowledge Graph Schema fuer pathOS Audit
-- Leichtgewichtig: SQLite mit JSON-Feldern

CREATE TABLE IF NOT EXISTS nodes (
    id TEXT PRIMARY KEY,
    type TEXT NOT NULL,  -- person, team, system, document, issue, metric, process
    name TEXT NOT NULL,
    summary TEXT,        -- Kurzbeschreibung (1-2 Saetze)
    properties TEXT,     -- JSON mit zusaetzlichen Attributen
    source TEXT,         -- Woher stammt die Info (Dateiname, URL)
    updated_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS edges (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    source_id TEXT NOT NULL,
    target_id TEXT NOT NULL,
    relation TEXT NOT NULL,  -- belongs_to, works_on, causes, depends_on, etc.
    properties TEXT,         -- JSON mit Gewicht, Zeitraum, etc.
    source TEXT,
    updated_at TEXT DEFAULT (datetime('now')),
    FOREIGN KEY (source_id) REFERENCES nodes(id),
    FOREIGN KEY (target_id) REFERENCES nodes(id)
);

CREATE TABLE IF NOT EXISTS summaries (
    id TEXT PRIMARY KEY,
    topic TEXT NOT NULL,      -- Thema/Kategorie
    content TEXT NOT NULL,    -- Zusammenfassung (kompakt, fuer Kontextsuche)
    detail_path TEXT,         -- Pfad zur vollen Datei
    tags TEXT,                -- Komma-separierte Tags
    updated_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS facts (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    subject TEXT NOT NULL,    -- Worauf bezieht sich der Fakt
    predicate TEXT NOT NULL,  -- Was wird ausgesagt
    value TEXT NOT NULL,      -- Der Wert/die Aussage
    confidence TEXT DEFAULT 'confirmed',  -- confirmed, estimated, outdated
    source TEXT,
    date TEXT,               -- Wann war das aktuell
    updated_at TEXT DEFAULT (datetime('now'))
);

-- Indizes fuer schnelle Suche
CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type);
CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(name);
CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source_id);
CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target_id);
CREATE INDEX IF NOT EXISTS idx_edges_relation ON edges(relation);
CREATE INDEX IF NOT EXISTS idx_summaries_topic ON summaries(topic);
CREATE INDEX IF NOT EXISTS idx_facts_subject ON facts(subject);

-- FTS (Full-Text-Search) fuer Kontextsuche
CREATE VIRTUAL TABLE IF NOT EXISTS summaries_fts USING fts5(
    topic, content, tags, content='summaries', content_rowid='rowid'
);

CREATE VIRTUAL TABLE IF NOT EXISTS facts_fts USING fts5(
    subject, predicate, value, content='facts', content_rowid='rowid'
);
