/**
 * Workforce SQLite schema.
 *
 * Unified workers+jobs+claims tables. Coexists with synapse/architects tables
 * (no DROP, no rename). Migration copies live data on first init.
 */
export const WORKFORCE_SCHEMA = `
CREATE TABLE IF NOT EXISTS workforce_workers (
  id               TEXT PRIMARY KEY,
  name             TEXT NOT NULL UNIQUE,
  role             TEXT,
  client           TEXT NOT NULL DEFAULT 'unknown',
  status           TEXT NOT NULL DEFAULT 'idle'
    CHECK(status IN ('idle','active','stale','retired')),
  budget_cap_usd   REAL NOT NULL DEFAULT 10.0,
  spent_usd        REAL NOT NULL DEFAULT 0.0,
  score            REAL NOT NULL DEFAULT 0.0,
  last_heartbeat   INTEGER NOT NULL DEFAULT 0,
  created_at       INTEGER NOT NULL DEFAULT (strftime('%s','now')*1000)
);

CREATE TABLE IF NOT EXISTS workforce_jobs (
  id               TEXT PRIMARY KEY,
  title            TEXT NOT NULL,
  tier             TEXT NOT NULL DEFAULT 'tactical'
    CHECK(tier IN ('strategy','tactical')),
  status           TEXT NOT NULL DEFAULT 'ready'
    CHECK(status IN ('backlog','ready','claimed','wip','blocked','review','done','failed','cancelled')),
  priority         INTEGER NOT NULL DEFAULT 5,
  worker_id        TEXT,
  parent_id        TEXT,
  depends_on       TEXT NOT NULL DEFAULT '[]',
  budget_cap_usd   REAL,
  tokens_used      INTEGER NOT NULL DEFAULT 0,
  payload          TEXT NOT NULL DEFAULT '{}',
  client           TEXT NOT NULL DEFAULT 'unknown',
  claimed_at       INTEGER,
  completed_at     INTEGER,
  created_at       INTEGER NOT NULL DEFAULT (strftime('%s','now')*1000)
);

CREATE TABLE IF NOT EXISTS workforce_claims (
  id               TEXT PRIMARY KEY,
  job_id           TEXT NOT NULL REFERENCES workforce_jobs(id) ON DELETE CASCADE,
  worker_id        TEXT NOT NULL,
  acquired_at      INTEGER NOT NULL DEFAULT (strftime('%s','now')*1000),
  released_at      INTEGER,
  lease_ms         INTEGER NOT NULL DEFAULT 300000,
  expires_at       INTEGER NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_wf_jobs_status       ON workforce_jobs(status, priority);
CREATE INDEX IF NOT EXISTS idx_wf_jobs_worker        ON workforce_jobs(worker_id, status);
CREATE INDEX IF NOT EXISTS idx_wf_jobs_parent        ON workforce_jobs(parent_id);
CREATE INDEX IF NOT EXISTS idx_wf_workers_status     ON workforce_workers(status, last_heartbeat);
CREATE INDEX IF NOT EXISTS idx_wf_claims_job         ON workforce_claims(job_id, released_at);
CREATE INDEX IF NOT EXISTS idx_wf_claims_expiry      ON workforce_claims(job_id, expires_at, released_at);

CREATE VIEW IF NOT EXISTS vw_kanban AS
  SELECT
    status AS lane,
    id, title, worker_id, priority, tokens_used,
    budget_cap_usd, client, created_at, claimed_at
  FROM workforce_jobs
  WHERE
    -- Active lanes: always show
    status NOT IN ('done', 'failed', 'cancelled')
    OR
    -- Terminal lanes: only show last 7 days to prevent unbounded growth
    completed_at > (strftime('%s','now') - 7*86400) * 1000
  ORDER BY
    CASE status
      WHEN 'backlog'   THEN 1
      WHEN 'ready'     THEN 2
      WHEN 'claimed'   THEN 3
      WHEN 'wip'       THEN 4
      WHEN 'blocked'   THEN 5
      WHEN 'review'    THEN 6
      WHEN 'done'      THEN 7
      WHEN 'failed'    THEN 8
      WHEN 'cancelled' THEN 9
      ELSE 10
    END,
    priority,
    created_at;

CREATE VIEW IF NOT EXISTS vw_worker_load AS
  SELECT
    w.id, w.name, w.role, w.status, w.client,
    COUNT(j.id)        AS active_jobs,
    COALESCE(SUM(j.tokens_used), 0) AS total_tokens,
    w.spent_usd,
    w.budget_cap_usd,
    w.last_heartbeat
  FROM workforce_workers w
  LEFT JOIN workforce_jobs j
    ON j.worker_id = w.id AND j.status IN ('claimed','wip','review')
  GROUP BY w.id;
`;
function hasColumn(db, table, column) {
    const rows = db.prepare(`PRAGMA table_info(${table})`).all();
    return rows.some((r) => r.name === column);
}
function addColIfMissing(db, table, col, ddl) {
    if (hasColumn(db, table, col))
        return;
    db.prepare(ddl).run();
}
export function initWorkforceSchema(db) {
    db.exec(WORKFORCE_SCHEMA);
    addColIfMissing(db, 'workforce_workers', 'company_id', "ALTER TABLE workforce_workers ADD COLUMN company_id TEXT NOT NULL DEFAULT 'default'");
    addColIfMissing(db, 'workforce_jobs', 'company_id', "ALTER TABLE workforce_jobs    ADD COLUMN company_id TEXT NOT NULL DEFAULT 'default'");
    db.exec('CREATE INDEX IF NOT EXISTS idx_wf_workers_company ON workforce_workers(company_id, status)');
    db.exec('CREATE INDEX IF NOT EXISTS idx_wf_jobs_company    ON workforce_jobs(company_id, status, priority)');
}
