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
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
import Database from 'better-sqlite3';
import path from 'path';
import fs from 'fs';
import { 
  type Document, 
  type InsertDocument,
  type SearchQuery,
  type InsertSearchQuery,
  type SearchResult,
  type InsertSearchResult,
  type Citation,
  type InsertCitation,
  type SearchRequest,
  type SearchResponse,
  type DocumentWithContext
} from "@shared/schema";
import { IStorage } from './storage';

export class SQLiteStorage implements IStorage {
  private db: Database.Database;

  constructor(dbPath?: string) {
    // Use /tmp for database in production environments (like Hugging Face Spaces)
    const defaultPath = process.env.NODE_ENV === 'production'
      ? '/tmp/knowledgebridge.db'
      : './data/knowledgebridge.db';
    
    const finalPath = dbPath || defaultPath;
    
    // Ensure data directory exists with error handling
    const dir = path.dirname(finalPath);
    try {
      if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
      }
    } catch (error) {
      console.warn(`Failed to create database directory at ${dir}:`, error);
    }

    this.db = new Database(finalPath);
    this.initializeTables();
  }

  private initializeTables() {
    // Enable foreign keys
    this.db.pragma('foreign_keys = ON');

    // Create documents table
    this.db.exec(`
      CREATE TABLE IF NOT EXISTS documents (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        title TEXT NOT NULL,
        content TEXT NOT NULL,
        source TEXT NOT NULL,
        source_type TEXT NOT NULL,
        url TEXT,
        metadata TEXT, -- JSON string
        embedding TEXT, -- JSON string
        file_path TEXT,
        file_name TEXT,
        file_size INTEGER,
        mime_type TEXT,
        processing_status TEXT NOT NULL DEFAULT 'pending',
        modal_task_id TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        processed_at DATETIME
      )
    `);

    // Create search_queries table
    this.db.exec(`
      CREATE TABLE IF NOT EXISTS search_queries (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        query TEXT NOT NULL,
        search_type TEXT NOT NULL DEFAULT 'semantic',
        filters TEXT, -- JSON string
        results_count INTEGER DEFAULT 0,
        search_time REAL,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
      )
    `);

    // Create search_results table
    this.db.exec(`
      CREATE TABLE IF NOT EXISTS search_results (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        query_id INTEGER NOT NULL,
        document_id INTEGER NOT NULL,
        relevance_score REAL NOT NULL,
        snippet TEXT NOT NULL,
        rank INTEGER NOT NULL,
        FOREIGN KEY (query_id) REFERENCES search_queries(id),
        FOREIGN KEY (document_id) REFERENCES documents(id)
      )
    `);

    // Create citations table
    this.db.exec(`
      CREATE TABLE IF NOT EXISTS citations (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        document_id INTEGER NOT NULL,
        citation_text TEXT NOT NULL,
        page_number INTEGER,
        section TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (document_id) REFERENCES documents(id)
      )
    `);

    // Create indexes for better performance
    this.db.exec(`
      CREATE INDEX IF NOT EXISTS idx_documents_source_type ON documents(source_type);
      CREATE INDEX IF NOT EXISTS idx_documents_processing_status ON documents(processing_status);
      CREATE INDEX IF NOT EXISTS idx_search_results_query_id ON search_results(query_id);
      CREATE INDEX IF NOT EXISTS idx_search_results_document_id ON search_results(document_id);
      CREATE INDEX IF NOT EXISTS idx_citations_document_id ON citations(document_id);
    `);
  }

  async getDocument(id: number): Promise<Document | undefined> {
    const stmt = this.db.prepare('SELECT * FROM documents WHERE id = ?');
    const row = stmt.get(id) as any;
    return row ? this.mapDocumentRow(row) : undefined;
  }

  async getDocuments(limit = 50, offset = 0): Promise<Document[]> {
    const stmt = this.db.prepare('SELECT * FROM documents ORDER BY created_at DESC LIMIT ? OFFSET ?');
    const rows = stmt.all(limit, offset) as any[];
    return rows.map(row => this.mapDocumentRow(row));
  }

  async createDocument(insertDocument: InsertDocument): Promise<Document> {
    const stmt = this.db.prepare(`
      INSERT INTO documents (
        title, content, source, source_type, url, metadata, embedding,
        file_path, file_name, file_size, mime_type, processing_status, modal_task_id
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `);

    const result = stmt.run(
      insertDocument.title,
      insertDocument.content,
      insertDocument.source,
      insertDocument.sourceType,
      insertDocument.url || null,
      insertDocument.metadata ? JSON.stringify(insertDocument.metadata) : null,
      insertDocument.embedding || null,
      (insertDocument as any).filePath || null,
      (insertDocument as any).fileName || null,
      (insertDocument as any).fileSize || null,
      (insertDocument as any).mimeType || null,
      (insertDocument as any).processingStatus || 'pending',
      (insertDocument as any).modalTaskId || null
    );

    const created = await this.getDocument(result.lastInsertRowid as number);
    if (!created) throw new Error('Failed to create document');
    return created;
  }

  async updateDocument(id: number, updateData: Partial<InsertDocument & { processingStatus?: string; modalTaskId?: string; processedAt?: Date }>): Promise<Document | undefined> {
    const existing = await this.getDocument(id);
    if (!existing) return undefined;

    const fields: string[] = [];
    const values: any[] = [];

    Object.entries(updateData).forEach(([key, value]) => {
      if (value !== undefined) {
        switch (key) {
          case 'sourceType':
            fields.push('source_type = ?');
            break;
          case 'processingStatus':
            fields.push('processing_status = ?');
            break;
          case 'modalTaskId':
            fields.push('modal_task_id = ?');
            break;
          case 'filePath':
            fields.push('file_path = ?');
            break;
          case 'fileName':
            fields.push('file_name = ?');
            break;
          case 'fileSize':
            fields.push('file_size = ?');
            break;
          case 'mimeType':
            fields.push('mime_type = ?');
            break;
          case 'processedAt':
            fields.push('processed_at = ?');
            value = value instanceof Date ? value.toISOString() : value;
            break;
          case 'metadata':
            fields.push('metadata = ?');
            value = value ? JSON.stringify(value) : null;
            break;
          default:
            fields.push(`${key} = ?`);
        }
        values.push(value);
      }
    });

    if (fields.length === 0) return existing;

    values.push(id);
    const stmt = this.db.prepare(`UPDATE documents SET ${fields.join(', ')} WHERE id = ?`);
    stmt.run(...values);

    return await this.getDocument(id);
  }

  async deleteDocument(id: number): Promise<boolean> {
    const stmt = this.db.prepare('DELETE FROM documents WHERE id = ?');
    const result = stmt.run(id);
    return result.changes > 0;
  }

  async searchDocuments(request: SearchRequest): Promise<SearchResponse> {
    const startTime = Date.now();
    
    let sql = `
      SELECT * FROM documents 
      WHERE (title LIKE ? OR content LIKE ?)
    `;
    const params: any[] = [`%${request.query}%`, `%${request.query}%`];

    // Add source type filter if specified
    if (request.filters?.sourceTypes?.length) {
      const placeholders = request.filters.sourceTypes.map(() => '?').join(',');
      sql += ` AND source_type IN (${placeholders})`;
      params.push(...request.filters.sourceTypes);
    }

    sql += ` ORDER BY 
      CASE 
        WHEN title LIKE ? THEN 1 
        WHEN content LIKE ? THEN 2 
        ELSE 3 
      END,
      created_at DESC
      LIMIT ? OFFSET ?
    `;
    
    params.push(`%${request.query}%`, `%${request.query}%`, request.limit, request.offset);

    const stmt = this.db.prepare(sql);
    const rows = stmt.all(...params) as any[];
    
    const results = rows.map((row, index) => {
      const doc = this.mapDocumentRow(row);
      return {
        ...doc,
        relevanceScore: this.calculateRelevanceScore(doc, request.query),
        snippet: this.extractSnippet(doc.content, request.query),
        rank: index + 1
      };
    });

    const searchTime = (Date.now() - startTime) / 1000;

    // Save search query
    const searchQuery = await this.createSearchQuery({
      query: request.query,
      searchType: request.searchType,
      filters: request.filters,
      resultsCount: results.length,
      searchTime
    });

    // Save search results
    for (const doc of results) {
      await this.createSearchResult({
        queryId: searchQuery.id,
        documentId: doc.id,
        relevanceScore: doc.relevanceScore,
        snippet: doc.snippet,
        rank: doc.rank
      });
    }

    return {
      results,
      totalCount: results.length,
      searchTime,
      query: request.query,
      queryId: searchQuery.id
    };
  }

  private calculateRelevanceScore(doc: Document, query: string): number {
    const queryLower = query.toLowerCase();
    const titleLower = doc.title.toLowerCase();
    const contentLower = doc.content.toLowerCase();
    
    let score = 0;
    
    // Exact title match gets highest score
    if (titleLower === queryLower) score += 1.0;
    else if (titleLower.includes(queryLower)) score += 0.8;
    
    // Content matches
    if (contentLower.includes(queryLower)) score += 0.3;
    
    // Word-by-word scoring
    const queryWords = queryLower.split(' ');
    queryWords.forEach(word => {
      if (titleLower.includes(word)) score += 0.2;
      if (contentLower.includes(word)) score += 0.1;
    });

    return Math.min(score, 1.0);
  }

  private extractSnippet(content: string, query: string, maxLength = 200): string {
    const queryLower = query.toLowerCase();
    const contentLower = content.toLowerCase();
    
    const index = contentLower.indexOf(queryLower);
    if (index === -1) {
      return content.substring(0, maxLength) + (content.length > maxLength ? '...' : '');
    }

    const start = Math.max(0, index - 50);
    const end = Math.min(content.length, index + queryLower.length + 150);
    
    let snippet = content.substring(start, end);
    if (start > 0) snippet = '...' + snippet;
    if (end < content.length) snippet = snippet + '...';
    
    return snippet;
  }

  async getDocumentsBySourceType(sourceType: string): Promise<Document[]> {
    const stmt = this.db.prepare('SELECT * FROM documents WHERE source_type = ? ORDER BY created_at DESC');
    const rows = stmt.all(sourceType) as any[];
    return rows.map(row => this.mapDocumentRow(row));
  }

  async getDocumentsByProcessingStatus(status: string): Promise<Document[]> {
    const stmt = this.db.prepare('SELECT * FROM documents WHERE processing_status = ? ORDER BY created_at DESC');
    const rows = stmt.all(status) as any[];
    return rows.map(row => this.mapDocumentRow(row));
  }

  async createSearchQuery(insertQuery: InsertSearchQuery): Promise<SearchQuery> {
    const stmt = this.db.prepare(`
      INSERT INTO search_queries (query, search_type, filters, results_count, search_time)
      VALUES (?, ?, ?, ?, ?)
    `);

    const result = stmt.run(
      insertQuery.query,
      insertQuery.searchType || 'semantic',
      insertQuery.filters ? JSON.stringify(insertQuery.filters) : null,
      insertQuery.resultsCount || null,
      insertQuery.searchTime || null
    );

    const created = this.db.prepare('SELECT * FROM search_queries WHERE id = ?').get(result.lastInsertRowid) as any;
    return this.mapSearchQueryRow(created);
  }

  async getSearchQueries(limit = 50): Promise<SearchQuery[]> {
    const stmt = this.db.prepare('SELECT * FROM search_queries ORDER BY created_at DESC LIMIT ?');
    const rows = stmt.all(limit) as any[];
    return rows.map(row => this.mapSearchQueryRow(row));
  }

  async createSearchResult(insertResult: InsertSearchResult): Promise<SearchResult> {
    const stmt = this.db.prepare(`
      INSERT INTO search_results (query_id, document_id, relevance_score, snippet, rank)
      VALUES (?, ?, ?, ?, ?)
    `);

    const result = stmt.run(
      insertResult.queryId,
      insertResult.documentId,
      insertResult.relevanceScore,
      insertResult.snippet,
      insertResult.rank
    );

    const created = this.db.prepare('SELECT * FROM search_results WHERE id = ?').get(result.lastInsertRowid) as any;
    return this.mapSearchResultRow(created);
  }

  async getSearchResults(queryId: number): Promise<SearchResult[]> {
    const stmt = this.db.prepare('SELECT * FROM search_results WHERE query_id = ? ORDER BY rank');
    const rows = stmt.all(queryId) as any[];
    return rows.map(row => this.mapSearchResultRow(row));
  }

  async createCitation(insertCitation: InsertCitation): Promise<Citation> {
    const stmt = this.db.prepare(`
      INSERT INTO citations (document_id, citation_text, page_number, section)
      VALUES (?, ?, ?, ?)
    `);

    const result = stmt.run(
      insertCitation.documentId,
      insertCitation.citationText,
      insertCitation.pageNumber || null,
      insertCitation.section || null
    );

    const created = this.db.prepare('SELECT * FROM citations WHERE id = ?').get(result.lastInsertRowid) as any;
    return this.mapCitationRow(created);
  }

  async getCitationsByDocument(documentId: number): Promise<Citation[]> {
    const stmt = this.db.prepare('SELECT * FROM citations WHERE document_id = ? ORDER BY created_at DESC');
    const rows = stmt.all(documentId) as any[];
    return rows.map(row => this.mapCitationRow(row));
  }

  async deleteCitation(id: number): Promise<boolean> {
    const stmt = this.db.prepare('DELETE FROM citations WHERE id = ?');
    const result = stmt.run(id);
    return result.changes > 0;
  }

  private mapDocumentRow(row: any): Document {
    return {
      id: row.id,
      title: row.title,
      content: row.content,
      source: row.source,
      sourceType: row.source_type,
      url: row.url,
      metadata: row.metadata ? JSON.parse(row.metadata) : null,
      embedding: row.embedding,
      createdAt: new Date(row.created_at),
      filePath: row.file_path,
      fileName: row.file_name,
      fileSize: row.file_size,
      mimeType: row.mime_type,
      processingStatus: row.processing_status,
      modalTaskId: row.modal_task_id,
      processedAt: row.processed_at ? new Date(row.processed_at) : null,
    } as Document;
  }

  private mapSearchQueryRow(row: any): SearchQuery {
    return {
      id: row.id,
      query: row.query,
      searchType: row.search_type,
      filters: row.filters ? JSON.parse(row.filters) : null,
      resultsCount: row.results_count,
      searchTime: row.search_time,
      createdAt: new Date(row.created_at)
    };
  }

  private mapSearchResultRow(row: any): SearchResult {
    return {
      id: row.id,
      queryId: row.query_id,
      documentId: row.document_id,
      relevanceScore: row.relevance_score,
      snippet: row.snippet,
      rank: row.rank
    };
  }

  private mapCitationRow(row: any): Citation {
    return {
      id: row.id,
      documentId: row.document_id,
      citationText: row.citation_text,
      pageNumber: row.page_number,
      section: row.section,
      createdAt: new Date(row.created_at)
    };
  }

  close() {
    this.db.close();
  }
}