package http

import (
	"encoding/json"
	"net/http"
	"strconv"

	"mind/internal/glue"
)

// POST /conversations  {"title":"demo","owner_id":1}
// GET  /conversations?owner_id=1
func (s *server) conversations(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case http.MethodPost:
		var in struct { Title string `json:"title"`; OwnerID int64 `json:"owner_id"` }
		if err := json.NewDecoder(r.Body).Decode(&in); err != nil { writeJSON(w, 400, map[string]string{"error":"bad json"}); return }
		id, err := s.glue.CreateConversation(r.Context(), in.OwnerID, in.Title)
		if err != nil { writeJSON(w, 500, map[string]string{"error": err.Error()}); return }
		writeJSON(w, 200, map[string]any{"id": id})
	case http.MethodGet:
		ownerStr := r.URL.Query().Get("owner_id")
		owner, _ := strconv.ParseInt(ownerStr, 10, 64)
		out, err := s.glue.ListConversations(r.Context(), owner)
		if err != nil { writeJSON(w, 500, map[string]string{"error": err.Error()}); return }
		writeJSON(w, 200, out)
	default:
		w.WriteHeader(405)
	}
}

// POST /branches {conversation_id, name, head_node_id}
// GET  /branches?conversation_id=...
// DELETE /branches {conversation_id, name}
func (s *server) branches(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case http.MethodPost:
		var in struct {
			ConversationID int64  `json:"conversation_id"`
			Name           string `json:"name"`
			HeadNodeID     int64  `json:"head_node_id"`
		}
		if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
			writeJSON(w, 400, map[string]string{"error": "bad json"}); return
		}
		b, err := s.glue.ForkBranch(r.Context(), glue.ForkReq{
			ConversationID: in.ConversationID,
			Name:           in.Name,
			HeadNodeID:     in.HeadNodeID,
		})
		if err != nil { writeJSON(w, 500, map[string]string{"error": err.Error()}); return }
		writeJSON(w, 200, b)

	case http.MethodGet:
		qs := r.URL.Query().Get("conversation_id")
		if qs == "" { writeJSON(w, 400, map[string]string{"error":"conversation_id required"}); return }
		convID, _ := strconv.ParseInt(qs, 10, 64)
		out, err := s.glue.ListBranches(r.Context(), convID)
		if err != nil { writeJSON(w, 500, map[string]string{"error": err.Error()}); return }
		writeJSON(w, 200, out)

	case http.MethodDelete:
		var in struct {
			ConversationID int64  `json:"conversation_id"`
			Name           string `json:"name"`
		}
		if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
			writeJSON(w, 400, map[string]string{"error":"bad json"}); return
		}
		if err := s.glue.DeleteBranch(r.Context(), in.ConversationID, in.Name); err != nil {
			writeJSON(w, 500, map[string]string{"error": err.Error()}); return
		}
		writeJSON(w, 200, map[string]string{"ok":"true"})

	default:
		w.WriteHeader(405)
	}
}

// POST /completion {conversation_id, branch, prompt}
func (s *server) completion(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost { w.WriteHeader(405); return }
	var in glue.CompletionReq
	if err := json.NewDecoder(r.Body).Decode(&in); err != nil { writeJSON(w, 400, map[string]string{"error":"bad json"}); return }
	resp, err := s.glue.AppendCompletion(r.Context(), in)
	if err != nil { writeJSON(w, 500, map[string]string{"error": err.Error()}); return }
	writeJSON(w, 200, resp)
}

// GET /linearize?conversation_id=..&branch=main
func (s *server) linearize(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet { w.WriteHeader(405); return }
	convID, _ := strconv.ParseInt(r.URL.Query().Get("conversation_id"), 10, 64)
	branch := r.URL.Query().Get("branch")
	out, err := s.glue.LinearizeByBranch(r.Context(), convID, branch)
	if err != nil { writeJSON(w, 500, map[string]string{"error": err.Error()}); return }
	writeJSON(w, 200, out)
}
