-- Add phase_metadata column for agentic workflow tracking
ALTER TABLE projects ADD COLUMN IF NOT EXISTS phase_metadata JSONB DEFAULT '{
  "currentPhase": "think",
  "completedPhases": [],
  "phaseStatus": "not_started",
  "activities": [],
  "metrics": {
    "totalDuration": 0,
    "phaseDurations": {},
    "iterationCount": 0
  }
}'::jsonb;

-- Create index for efficient querying
CREATE INDEX IF NOT EXISTS idx_projects_phase_metadata ON projects USING gin(phase_metadata);

-- Add comment for documentation
COMMENT ON COLUMN projects.phase_metadata IS 'Stores agentic development loop state: currentPhase, completedPhases, phaseStatus, activities, metrics';

-- Create function to update phase
CREATE OR REPLACE FUNCTION update_project_phase(
  p_project_id UUID,
  p_new_phase TEXT,
  p_status TEXT DEFAULT 'in_progress'
)
RETURNS JSONB AS $$
DECLARE
  v_current_metadata JSONB;
  v_current_phase TEXT;
  v_completed_phases JSONB;
  v_new_activity JSONB;
  v_updated_metadata JSONB;
BEGIN
  -- Get current metadata
  SELECT phase_metadata INTO v_current_metadata
  FROM projects WHERE id = p_project_id;

  v_current_phase := v_current_metadata->>'currentPhase';
  v_completed_phases := COALESCE(v_current_metadata->'completedPhases', '[]'::jsonb);

  -- Add current phase to completed if transitioning
  IF v_current_phase IS NOT NULL AND v_current_phase != p_new_phase THEN
    v_completed_phases := v_completed_phases || to_jsonb(v_current_phase);
  END IF;

  -- Create activity record
  v_new_activity := jsonb_build_object(
    'id', gen_random_uuid(),
    'type', 'phase_change',
    'message', 'Transitioned to ' || p_new_phase || ' phase',
    'timestamp', now()
  );

  -- Build updated metadata
  v_updated_metadata := jsonb_build_object(
    'currentPhase', p_new_phase,
    'completedPhases', v_completed_phases,
    'phaseStatus', p_status,
    'activities', (v_new_activity || COALESCE(v_current_metadata->'activities', '[]'::jsonb))[0:49],
    'metrics', COALESCE(v_current_metadata->'metrics', '{}'::jsonb)
  );

  -- Update project
  UPDATE projects
  SET phase_metadata = v_updated_metadata, updated_at = now()
  WHERE id = p_project_id;

  RETURN v_updated_metadata;
END;
$$ LANGUAGE plpgsql;
