import sqlite3 from 'sqlite3';
import { open } from 'sqlite';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const DB_PATH = path.join(__dirname, '../../database/sqdc.db');

export async function initDB() {
  const db = await open({
    filename: DB_PATH,
    driver: sqlite3.Database
  });

  await db.exec(`
    CREATE TABLE IF NOT EXISTS categories (
      id INTEGER PRIMARY KEY,
      name TEXT NOT NULL,
      emoji TEXT,
      description TEXT
    );

    CREATE TABLE IF NOT EXISTS kpis (
      id INTEGER PRIMARY KEY,
      category_id INTEGER NOT NULL,
      name TEXT NOT NULL,
      unit TEXT,
      target REAL,
      formula TEXT,
      description TEXT,
      frequency TEXT,
      FOREIGN KEY(category_id) REFERENCES categories(id)
    );

    CREATE TABLE IF NOT EXISTS measurements (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      kpi_id INTEGER NOT NULL,
      measurement_date DATETIME NOT NULL,
      value REAL NOT NULL,
      status TEXT,
      FOREIGN KEY(kpi_id) REFERENCES kpis(id)
    );

    CREATE TABLE IF NOT EXISTS alerts (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      kpi_id INTEGER NOT NULL,
      alert_type TEXT,
      severity TEXT,
      message TEXT,
      created_at DATETIME,
      FOREIGN KEY(kpi_id) REFERENCES kpis(id)
    );

    CREATE INDEX IF NOT EXISTS idx_measurements_kpi ON measurements(kpi_id);
    CREATE INDEX IF NOT EXISTS idx_measurements_date ON measurements(measurement_date);
    CREATE INDEX IF NOT EXISTS idx_alerts_kpi ON alerts(kpi_id);
  `);

  return db;
}

export async function getKPIs(db) {
  return await db.all('SELECT * FROM kpis');
}

export async function getMeasurements(db, kpiId, days = 30) {
  const fromDate = new Date();
  fromDate.setDate(fromDate.getDate() - days);
  
  return await db.all(
    'SELECT * FROM measurements WHERE kpi_id = ? AND measurement_date >= ? ORDER BY measurement_date ASC',
    [kpiId, fromDate.toISOString()]
  );
}

export async function getLatestMeasurement(db, kpiId) {
  return await db.get(
    'SELECT * FROM measurements WHERE kpi_id = ? ORDER BY measurement_date DESC LIMIT 1',
    [kpiId]
  );
}
