-- ============================================================
-- A0 Software Orchestrator – Patterns-Bibliothek
-- SQLite Schema v1.0.0
-- ============================================================

-- -----------------------------------------------------------
-- 1. PROJEKT-REGISTRY (zentrale Projekt-Liste)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS projects_registry (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    
    -- Identifikation
    project_name TEXT NOT NULL UNIQUE,
    project_path TEXT NOT NULL,
    git_url TEXT,
    
    -- Status
    status TEXT NOT NULL DEFAULT 'active',
        -- active, paused, completed, archived, failed
    phase TEXT,
        -- intake, requirements, architecture, implementation,
        -- testing, deployment, maintenance
    plan_mode TEXT,
        -- planning_only, implementation_allowed,
        -- runtime_verification_allowed, deployment_preparation_allowed,
        -- release_handoff_allowed, maintenance_allowed
    
    -- Tech-Stack (JSON)
    tech_stack TEXT,
        -- {"backend":"FastAPI","frontend":"React","db":"SQLite",
        --  "orm":"SQLAlchemy","docker":true}
    
    -- Metriken
    total_tasks INTEGER DEFAULT 0,
    completed_tasks INTEGER DEFAULT 0,
    open_errors INTEGER DEFAULT 0,
    
    -- Zeitstempel
    created_at TEXT DEFAULT (datetime('now')),
    started_at TEXT,
    last_active_at TEXT DEFAULT (datetime('now')),
    completed_at TEXT,
    
    -- Verknüpfung zur Patterns-Bibliothek
    patterns_extracted INTEGER DEFAULT 0,
    last_extraction_at TEXT,
    
    -- Notizen
    description TEXT,
    notes TEXT
);

CREATE INDEX IF NOT EXISTS idx_projects_status   ON projects_registry(status, phase);
CREATE INDEX IF NOT EXISTS idx_projects_active   ON projects_registry(last_active_at);
CREATE INDEX IF NOT EXISTS idx_projects_tech     ON projects_registry(tech_stack);

-- -----------------------------------------------------------
-- 2. PATTERNS (das eigentliche Wissen)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS patterns (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    
    -- Basis
    title TEXT NOT NULL,
    category TEXT NOT NULL,
        -- docker, python, frontend, deployment, error_fix,
        -- architecture, framework, workflow, database, security
    subcategory TEXT,
        -- z.B. 'fastapi', 'react', 'sqlalchemy', 'postgresql'
    pattern_type TEXT NOT NULL,
        -- code_snippet, architecture_decision, error_solution,
        -- best_practice, setup_guide, deployment_config,
        -- workflow_pattern, anti_pattern
    
    -- Inhalt
    description TEXT NOT NULL,
    code_example TEXT,
    when_to_use TEXT,
    why_it_works TEXT,
    pitfalls TEXT,
    
    -- Meta
    source_project_id INTEGER REFERENCES projects_registry(id),
    source_task_id TEXT,
    source_error TEXT,
    source_file TEXT,
    
    -- Qualität & Validierung
    validated INTEGER DEFAULT 0,
        -- 0 = automatisch extrahiert, ungeprüft
        -- 1 = durch quality_reviewer bestätigt
        -- 2 = manuell erstellt/geprüft
        -- -1 = veraltet/deprecated
    validation_date TEXT,
    validated_by TEXT,
    
    -- Nutzungs-Statistik
    usage_count INTEGER DEFAULT 0,
    success_count  INTEGER DEFAULT 0,
    failure_count  INTEGER DEFAULT 0,
    success_rate   REAL DEFAULT 0.0,
    
    -- Aging
    staleness_score REAL DEFAULT 0.0,
        -- 0.0 = frisch, 1.0 = stark veraltet
    framework_version TEXT,
        -- z.B. "FastAPI 0.115", "React 19", "Python 3.12"
    
    -- Zeitstempel
    created_at   TEXT DEFAULT (datetime('now')),
    updated_at   TEXT DEFAULT (datetime('now')),
    last_used_at TEXT
);

CREATE INDEX IF NOT EXISTS idx_patterns_category ON patterns(category, pattern_type);
CREATE INDEX IF NOT EXISTS idx_patterns_project  ON patterns(source_project_id);
CREATE INDEX IF NOT EXISTS idx_patterns_valid    ON patterns(validated);
CREATE INDEX IF NOT EXISTS idx_patterns_stale    ON patterns(staleness_score);

-- -----------------------------------------------------------
-- 3. TAGS (flexible Verschlagwortung)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS tags (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT UNIQUE NOT NULL
);

CREATE TABLE IF NOT EXISTS pattern_tags (
    pattern_id INTEGER REFERENCES patterns(id) ON DELETE CASCADE,
    tag_id     INTEGER REFERENCES tags(id) ON DELETE CASCADE,
    PRIMARY KEY (pattern_id, tag_id)
);

-- -----------------------------------------------------------
-- 4. PATTERN-BEZIEHUNGEN
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS pattern_relations (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    pattern_a_id INTEGER REFERENCES patterns(id) ON DELETE CASCADE,
    pattern_b_id INTEGER REFERENCES patterns(id) ON DELETE CASCADE,
    relation_type TEXT NOT NULL,
        -- 'often_used_with', 'alternative_to', 'depends_on',
        -- 'replaces', 'is_replaced_by', 'conflicts_with'
    strength REAL DEFAULT 1.0,
    notes TEXT,
    created_at TEXT DEFAULT (datetime('now')),
    UNIQUE(pattern_a_id, pattern_b_id, relation_type)
);

-- -----------------------------------------------------------
-- 5. PATTERN-KONFLIKTE (widersprüchliche Patterns)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS pattern_conflicts (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    pattern_a_id INTEGER REFERENCES patterns(id) ON DELETE CASCADE,
    pattern_b_id INTEGER REFERENCES patterns(id) ON DELETE CASCADE,
    conflict_type TEXT NOT NULL,
        -- 'direct_contradiction', 'context_dependent', 'version_specific'
    description TEXT,
    resolution_context TEXT,
        -- JSON: {"if": "high_traffic", "use": "A", "if": "simple", "use": "B"}
    resolved_by TEXT DEFAULT 'system',
        -- 'system', 'quality_reviewer', 'manual'
    resolved_at TEXT,
    created_at TEXT DEFAULT (datetime('now'))
);

-- -----------------------------------------------------------
-- 6. PATTERN-FEEDBACK (negative + positive Lernerfahrungen)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS pattern_feedback (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    pattern_id INTEGER REFERENCES patterns(id) ON DELETE CASCADE,
    project_id INTEGER REFERENCES projects_registry(id),
    
    outcome TEXT NOT NULL,
        -- 'success', 'failure', 'partial_success', 'not_applicable'
    reason TEXT,
    context_diff TEXT,
        -- Was war anders als beim ursprünglichen Pattern?
    
    -- Bei Fehlschlag: Was wurde stattdessen verwendet?
    alternative_used TEXT,
    alternative_pattern_id INTEGER REFERENCES patterns(id),
    
    created_at TEXT DEFAULT (datetime('now'))
);

CREATE INDEX IF NOT EXISTS idx_feedback_pattern ON pattern_feedback(pattern_id);
CREATE INDEX IF NOT EXISTS idx_feedback_project ON pattern_feedback(project_id);

-- -----------------------------------------------------------
-- 7. LERN-LOG (Historie für Debugging)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS learn_log (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    pattern_id INTEGER REFERENCES patterns(id),
    project_id INTEGER REFERENCES projects_registry(id),
    
    trigger TEXT NOT NULL,
        -- 'task_completed', 'error_fixed', 'deployment_success',
        -- 'decision_made', 'release_audit', 'manual_entry'
    source_file TEXT,
    source_content_hash TEXT,
    
    extracted_at TEXT DEFAULT (datetime('now'))
);

-- -----------------------------------------------------------
-- 8. SCHEMA-VERSION (Migration-Tracking)
-- -----------------------------------------------------------
CREATE TABLE IF NOT EXISTS schema_version (
    version INTEGER PRIMARY KEY,
    description TEXT,
    applied_at TEXT DEFAULT (datetime('now'))
);

-- Initiale Version eintragen
INSERT OR IGNORE INTO schema_version (version, description) 
VALUES (1, 'Initiales Schema: patterns, projects_registry, tags, relations, conflicts, feedback, learn_log');

-- -----------------------------------------------------------
-- 9. FTS5 VOLLTEXT-INDEX
-- -----------------------------------------------------------
CREATE VIRTUAL TABLE IF NOT EXISTS patterns_fts USING fts5(
    title,
    description,
    code_example,
    when_to_use,
    why_it_works,
    pitfalls,
    content='patterns',
    content_rowid='id'
);

-- Trigger: Automatische FTS-Synchronisation
CREATE TRIGGER IF NOT EXISTS patterns_ai AFTER INSERT ON patterns BEGIN
    INSERT INTO patterns_fts(rowid, title, description, code_example, when_to_use, why_it_works, pitfalls)
    VALUES (new.id, new.title, new.description, new.code_example, new.when_to_use, new.why_it_works, new.pitfalls);
END;

CREATE TRIGGER IF NOT EXISTS patterns_ad AFTER DELETE ON patterns BEGIN
    INSERT INTO patterns_fts(patterns_fts, rowid, title, description, code_example, when_to_use, why_it_works, pitfalls)
    VALUES ('delete', old.id, old.title, old.description, old.code_example, old.when_to_use, old.why_it_works, old.pitfalls);
END;

CREATE TRIGGER IF NOT EXISTS patterns_au AFTER UPDATE ON patterns BEGIN
    INSERT INTO patterns_fts(patterns_fts, rowid, title, description, code_example, when_to_use, why_it_works, pitfalls)
    VALUES ('delete', old.id, old.title, old.description, old.code_example, old.when_to_use, old.why_it_works, old.pitfalls);
    INSERT INTO patterns_fts(rowid, title, description, code_example, when_to_use, why_it_works, pitfalls)
    VALUES (new.id, new.title, new.description, new.code_example, new.when_to_use, new.why_it_works, new.pitfalls);
END;

-- -----------------------------------------------------------
-- 10. VEKTOR-TABELLE (sqlite-vec, optional)
-- -----------------------------------------------------------
-- Wird von db.py dynamisch erstellt, wenn sqlite-vec verfügbar ist.
-- CREATE VIRTUAL TABLE IF NOT EXISTS pattern_embeddings USING vec0(
--     embedding float[384]  -- all-MiniLM-L6-v2 (Standard-Modell)
-- );

-- ============================================================
-- NÜTZLICHE VIEWS
-- ============================================================

-- Aktive Projekt-Übersicht
CREATE VIEW IF NOT EXISTS v_active_projects AS
SELECT 
    project_name,
    status,
    phase,
    completed_tasks || '/' || total_tasks AS progress,
    open_errors,
    patterns_extracted,
    last_active_at
FROM projects_registry
WHERE status = 'active'
ORDER BY last_active_at DESC;

-- Validierten Patterns mit Nutzungsstatistik
CREATE VIEW IF NOT EXISTS v_ready_patterns AS
SELECT 
    p.id, p.title, p.category, p.pattern_type,
    p.usage_count, p.success_count, p.failure_count,
    CASE WHEN p.success_count + p.failure_count > 0 
         THEN ROUND(p.success_count * 100.0 / (p.success_count + p.failure_count), 1)
         ELSE NULL END AS success_pct,
    p.staleness_score,
    p.created_at, p.last_used_at
FROM patterns p
WHERE p.validated >= 0  -- Nur aktive, nicht deprecated
ORDER BY p.usage_count DESC;

-- Konflikt-Übersicht
CREATE VIEW IF NOT EXISTS v_conflicts AS
SELECT 
    pc.id,
    a.title AS pattern_a,
    b.title AS pattern_b,
    pc.conflict_type,
    pc.resolution_context,
    pc.resolved_by
FROM pattern_conflicts pc
JOIN patterns a ON pc.pattern_a_id = a.id
JOIN patterns b ON pc.pattern_b_id = b.id;
