package server

import (
	"fmt"
	"net/http"

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
	"github.com/daniel/cursor-adapter/internal/bridge"
	"github.com/daniel/cursor-adapter/internal/config"
)

type Server struct {
	cfg *config.Config
	br  bridge.Bridge
	mux *chi.Mux
}

func New(cfg *config.Config, br bridge.Bridge) *Server {
	s := &Server{cfg: cfg, br: br}
	s.mux = s.buildRouter()
	return s
}

func corsMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Cursor-Session-ID, X-Cursor-Workspace")
		w.Header().Set("Access-Control-Expose-Headers", "X-Cursor-Session-ID")

		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusNoContent)
			return
		}

		next.ServeHTTP(w, r)
	})
}

func (s *Server) buildRouter() *chi.Mux {
	r := chi.NewRouter()
	r.Use(middleware.Recoverer)
	r.Use(middleware.Logger)
	r.Use(corsMiddleware)

	r.Get("/v1/models", s.handleListModels)
	r.Post("/v1/chat/completions", s.handleChatCompletions)
	r.Post("/v1/messages", s.handleAnthropicMessages)
	r.Get("/health", s.handleHealth)

	return r
}

func (s *Server) Run() error {
	addr := fmt.Sprintf("127.0.0.1:%d", s.cfg.Port)
	return http.ListenAndServe(addr, s.mux)
}
