package workbench

import (
	"context"
	"regexp"
	"encoding/json"
	"errors"
	"net/http"
	"strings"

	"aigateway.local/core/internal/identity"
	"aigateway.local/core/internal/platform/apiresponse"
	"aigateway.local/core/internal/platform/cryptox"
	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgxpool"
)

// EnvVarService 管理门户用户个人环境变量(值加密存储)。
type EnvVarService struct {
	pool   *pgxpool.Pool
	cipher cryptox.Cipher
}

func NewEnvVarService(pool *pgxpool.Pool, cipher cryptox.Cipher) *EnvVarService {
	return &EnvVarService{pool: pool, cipher: cipher}
}

// List 返回用户环境变量(键列表,不含值)。
func (s *EnvVarService) List(ctx context.Context, userID string) ([]map[string]any, error) {
	if s == nil || s.pool == nil {
		return nil, errors.New("环境变量服务不可用")
	}
	rows, err := s.pool.Query(ctx, `SELECT key,octet_length(encrypted_value)>0,updated_at FROM gateway.user_env_vars WHERE portal_user_id=$1 ORDER BY key`, userID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []map[string]any{}
	for rows.Next() {
		var key string
		var hasValue bool
		var updatedAt any
		if err := rows.Scan(&key, &hasValue, &updatedAt); err != nil {
			return nil, err
		}
		items = append(items, map[string]any{"key": key, "configured": hasValue, "updated_at": updatedAt})
	}
	return items, rows.Err()
}

// Upsert 设置一个环境变量;value 为空时删除。
func (s *EnvVarService) Upsert(ctx context.Context, userID, key, value string) error {
	if s == nil || s.pool == nil || s.cipher == nil {
		return errors.New("环境变量服务不可用")
	}
	key = strings.TrimSpace(key)
	if key == "" || len(key) > 128 || !envKeyPattern.MatchString(key) {
		return errors.New("变量名必须以字母开头,可含字母/数字/下划线,最长 128 字符")
	}
	if len(value) > 4096 {
		return errors.New("变量值过长")
	}
	value = strings.TrimSpace(value)
	if value == "" {
		tag, err := s.pool.Exec(ctx, `DELETE FROM gateway.user_env_vars WHERE portal_user_id=$1 AND key=$2`, userID, key)
		if err != nil {
			return err
		}
		if tag.RowsAffected() == 0 {
			return errors.New("变量不存在")
		}
		return nil
	}
	encrypted, version, err := s.cipher.Encrypt([]byte(value))
	if err != nil {
		return err
	}
	_, err = s.pool.Exec(ctx, `INSERT INTO gateway.user_env_vars(portal_user_id,key,encrypted_value,value_kek_version) VALUES($1,$2,$3,$4)
		ON CONFLICT(portal_user_id,key) DO UPDATE SET encrypted_value=$3,value_kek_version=$4,updated_at=clock_timestamp()`,
		userID, key, encrypted, version)
	return err
}

// Decrypt 解密单个变量(运行时合并用);不存在返回 ok=false。
func (s *EnvVarService) Decrypt(ctx context.Context, userID, key string) (string, bool, error) {
	if s == nil || s.pool == nil || s.cipher == nil {
		return "", false, nil
	}
	var encrypted []byte
	var version int
	err := s.pool.QueryRow(ctx, `SELECT encrypted_value,value_kek_version FROM gateway.user_env_vars WHERE portal_user_id=$1 AND key=$2`, userID, key).Scan(&encrypted, &version)
	if errors.Is(err, pgx.ErrNoRows) {
		return "", false, nil
	}
	if err != nil {
		return "", false, err
	}
	plaintext, err := s.cipher.Decrypt(encrypted, version)
	if err != nil {
		return "", false, err
	}
	return string(plaintext), true, nil
}

// MergeVariables 把用户环境变量合并进请求变量(请求未提供的键)。
func (s *EnvVarService) MergeVariables(ctx context.Context, userID string, variables map[string]any) error {
	if userID == "" || len(variables) >= 100 {
		return nil
	}
	rows, err := s.pool.Query(ctx, `SELECT key,encrypted_value,value_kek_version FROM gateway.user_env_vars WHERE portal_user_id=$1 LIMIT 200`, userID)
	if err != nil {
		return err
	}
	defer rows.Close()
	type pair struct{ key string; value []byte; version int }
	pairs := []pair{}
	for rows.Next() {
		var p pair
		if err := rows.Scan(&p.key, &p.value, &p.version); err != nil {
			return err
		}
		pairs = append(pairs, p)
	}
	if err := rows.Err(); err != nil {
		return err
	}
	for _, p := range pairs {
		if _, exists := variables[p.key]; exists {
			continue
		}
		plaintext, err := s.cipher.Decrypt(p.value, p.version)
		if err != nil {
			continue
		}
		variables[p.key] = string(plaintext)
	}
	return nil
}

var envKeyPattern = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9_]{0,127}$`)

// EnvVarHTTPHandler 门户环境变量 CRUD。
type EnvVarHTTPHandler struct {
	service  *EnvVarService
	identity *identity.Service
	mux      *http.ServeMux
}

func NewEnvVarHTTPHandler(service *EnvVarService, identityService *identity.Service) *EnvVarHTTPHandler {
	h := &EnvVarHTTPHandler{service: service, identity: identityService, mux: http.NewServeMux()}
	h.mux.HandleFunc("GET /api/v1/portal/env-vars", h.list)
	h.mux.HandleFunc("PUT /api/v1/portal/env-vars/{key}", h.upsert)
	h.mux.HandleFunc("DELETE /api/v1/portal/env-vars/{key}", h.delete)
	return h
}

func (h *EnvVarHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.mux.ServeHTTP(w, r) }

func (h *EnvVarHTTPHandler) account(w http.ResponseWriter, r *http.Request) (identity.Account, bool) {
	account, err := h.identity.Authenticate(r.Context(), identity.KindPortal, r.Header.Get("Authorization"))
	if err != nil {
		apiresponse.Error(w, http.StatusUnauthorized, "登录状态无效或已过期")
		return identity.Account{}, false
	}
	return account, true
}

func (h *EnvVarHTTPHandler) list(w http.ResponseWriter, r *http.Request) {
	a, ok := h.account(w, r)
	if !ok {
		return
	}
	items, err := h.service.List(r.Context(), a.ID)
	if err != nil {
		apiresponse.Error(w, http.StatusServiceUnavailable, "环境变量查询失败")
		return
	}
	apiresponse.OK(w, items)
}

func (h *EnvVarHTTPHandler) upsert(w http.ResponseWriter, r *http.Request) {
	a, ok := h.account(w, r)
	if !ok {
		return
	}
	var input struct {
		Value string `json:"value"`
	}
	decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
	decoder.DisallowUnknownFields()
	if decoder.Decode(&input) != nil {
		apiresponse.Error(w, http.StatusBadRequest, "请求格式无效")
		return
	}
	if err := h.service.Upsert(r.Context(), a.ID, r.PathValue("key"), input.Value); err != nil {
		apiresponse.Error(w, http.StatusBadRequest, err.Error())
		return
	}
	apiresponse.OK(w, map[string]bool{"saved": true})
}

func (h *EnvVarHTTPHandler) delete(w http.ResponseWriter, r *http.Request) {
	a, ok := h.account(w, r)
	if !ok {
		return
	}
	if err := h.service.Upsert(r.Context(), a.ID, r.PathValue("key"), ""); err != nil {
		apiresponse.Error(w, http.StatusBadRequest, err.Error())
		return
	}
	apiresponse.OK(w, map[string]bool{"deleted": true})
}
