import { useState } from 'react';

export function useRuntimeActions({ refresh, setChat }) {
  const [approvalBusyId, setApprovalBusyId] = useState(null);
  const [runtimeOpen, setRuntimeOpen] = useState(false);
  const [runtimeActionBusy, setRuntimeActionBusy] = useState(null);

  async function approveClaudeRun(runId) {
    if (!runId || approvalBusyId) return;
    setApprovalBusyId(runId);
    let agentText = 'Approved Claude Code run. Starting local execution...\n';
    setChat(c => [...c, { role: 'agent', text: agentText }]);

    try {
      const res = await fetch('/api/runs/approve-claude-run', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ run_id: runId }),
      });

      if (!res.ok || !res.body) {
        let message = await res.text();
        try { message = JSON.parse(message).error || message; } catch {}
        setChat(c => {
          const next = [...c];
          next[next.length - 1] = { role: 'agent', text: `${agentText}\n${message}` };
          return next;
        });
        await refresh();
        return;
      }

      const reader = res.body.getReader();
      const dec = new TextDecoder();
      let buf = '';

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        buf += dec.decode(value, { stream: true });
        const lines = buf.split('\n');
        buf = lines.pop();

        let eventName = '';
        for (const line of lines) {
          if (line.startsWith('event:')) {
            eventName = line.slice(6).trim();
          } else if (line.startsWith('data:')) {
            try {
              const payload = JSON.parse(line.slice(5).trim());
              if (eventName === 'stdout' && payload.line) agentText += `${payload.line}\n`;
              else if (eventName === 'stderr' && payload.line) agentText += `stderr: ${payload.line}\n`;
              else if (eventName === 'done') agentText += `\nClaude run ${payload.status}.`;
              else if (eventName === 'error') agentText += `\nError: ${payload.message}`;
              setChat(c => {
                const next = [...c];
                next[next.length - 1] = { role: 'agent', text: agentText };
                return next;
              });
            } catch {}
            eventName = '';
          }
        }
      }

      await refresh();
    } catch (error) {
      setChat(c => {
        const next = [...c];
        next[next.length - 1] = { role: 'agent', text: `${agentText}\nAction failed: ${error.message}` };
        return next;
      });
    } finally {
      setApprovalBusyId(null);
    }
  }

  async function decideGenericApproval(approvalId, decision) {
    if (!approvalId || approvalBusyId) return;
    setApprovalBusyId(approvalId);
    try {
      const res = await fetch(`/api/approvals/${encodeURIComponent(approvalId)}`, {
        method: 'PATCH',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ decision }),
      });
      if (!res.ok) throw new Error(await res.text());
      await refresh();
    } catch (error) {
      setChat(c => [...c, { role: 'agent', text: `Approval update failed: ${error.message}` }]);
    } finally {
      setApprovalBusyId(null);
    }
  }

  async function ensureOpsAgentAction() {
    setRuntimeActionBusy('ops');
    try {
      const res = await fetch('/api/agents/ops', { method: 'POST' });
      if (!res.ok) throw new Error(await res.text());
      setChat(c => [...c, { role: 'agent', text: 'Caretaker is ready: daily 08:00 schedule, scoped tools, and approval gates configured.' }]);
      await refresh();
    } catch (error) {
      setChat(c => [...c, { role: 'agent', text: `Caretaker setup failed: ${error.message}` }]);
    } finally {
      setRuntimeActionBusy(null);
    }
  }

  async function processHeartbeatOnceAction() {
    setRuntimeActionBusy('worker');
    try {
      const res = await fetch('/api/heartbeat/worker', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });
      if (!res.ok) throw new Error(await res.text());
      const result = await res.json();
      setChat(c => [...c, { role: 'agent', text: `Heartbeat worker processed once: ${result.worked ? result.status || 'worked' : 'no queued task'}.` }]);
      await refresh();
    } catch (error) {
      setChat(c => [...c, { role: 'agent', text: `Heartbeat worker failed: ${error.message}` }]);
    } finally {
      setRuntimeActionBusy(null);
    }
  }

  return {
    approvalBusyId,
    runtimeOpen,
    setRuntimeOpen,
    runtimeActionBusy,
    approveClaudeRun,
    decideGenericApproval,
    ensureOpsAgentAction,
    processHeartbeatOnceAction,
  };
}
