import { getDb, nowIso, newId } from './db.js';
import { publishStateChanged } from './live-events.js';
export const MISSION_TEMPLATES = [
 { slug:'weekly-project-pulse', name:'Weekly Project Pulse', target_role:'project_watcher', cadence:'Mondays 09:00', prompt:'Summarize open issues, PRs, library updates, and deploy status across this project.' },
 { slug:'draft-email-response', name:'Draft Email Response', target_role:'personal_assistant', cadence:'On demand', prompt:'Draft a reply to this inbox thread. Do not send. Return the draft only.' },
 { slug:'transcribe-and-summarize', name:'Transcribe and Summarize', target_role:'meeting_notes', cadence:'On audio upload', prompt:'Transcribe the audio file and produce action items, decisions, follow-ups, and attendees.' },
 { slug:'deploy-preview', name:'Deploy Preview', target_role:'engineering_lead', cadence:'On demand', prompt:'Run a preview deploy with explicit approval before executing.' },
];
export function listMissions(projectId) {
 const db=getDb(); const runs = db.prepare('SELECT * FROM missions WHERE (? IS NULL OR project_id = ?) ORDER BY created_at DESC LIMIT 50').all(projectId || null, projectId || null);
 return { templates: MISSION_TEMPLATES, runs };
}
export function runMission(slug, projectId, opts = {}) {
 if (typeof projectId === 'object' && projectId) { opts = { ...projectId, ...(opts || {}) }; projectId = opts.project_id || opts.projectId; }
 const tpl = MISSION_TEMPLATES.find(t => t.slug === slug); if (!tpl) throw new Error('mission template not found');
 const db=getDb(); const agent = db.prepare(`SELECT a.* FROM agents a JOIN agent_template_installations i ON i.agent_id = a.id WHERE i.project_id = ? AND a.role = ? AND i.status = 'active' LIMIT 1`).get(projectId, tpl.target_role);
 if (!agent) return { ok:false, error:'target agent is not installed for this project' };
  const now=nowIso(); const missionId=newId('mission'); const taskId=newId('hbtask'); const payload={ type:'mission', mission_id: missionId, task_id: taskId, agent_id: agent.id, slug, project_id: projectId, opts, prompt: tpl.prompt };
  db.prepare(`INSERT INTO missions (id, slug, project_id, agent_id, status, opts_json, task_id, created_at, updated_at) VALUES (?, ?, ?, ?, 'queued', ?, ?, ?, ?)`).run(missionId, slug, projectId, agent.id, JSON.stringify(opts), taskId, now, now);
  db.prepare(`INSERT INTO heartbeat_tasks (id, agent_id, type, status, priority, payload, attempts, max_attempts, run_after, project_id, created_at, updated_at) VALUES (?, ?, 'mission', 'queued', 10, ?, 0, 3, ?, ?, ?, ?)`).run(taskId, agent.id, JSON.stringify(payload), now, projectId, now, now);
 try { publishStateChanged('heartbeat'); } catch { /* observation-only */ }
 return { ok:true, mission_id: missionId, task_id: taskId, heartbeat_task_id: taskId, status:'queued', project_id: projectId, agent_id: agent.id };
}
export function markMissionFromTask(taskId, status, error = null) {
 const db=getDb(); const now=nowIso(); const next = status === 'complete' ? 'complete' : 'error';
 db.prepare('UPDATE missions SET status = ?, completed_at = CASE WHEN ? = \'complete\' THEN ? ELSE completed_at END, error = ?, updated_at = ? WHERE task_id = ?').run(next, next, now, error, now, taskId);
 try { publishStateChanged('heartbeat'); } catch { /* observation-only */ }
}
