package formhandler

import (
	"bytes"
	"context"
	"crypto/rand"
	"crypto/subtle"
	"database/sql"
	"embed"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"html/template"
	"image"
	"image/gif"
	"image/jpeg"
	"image/png"
	"io"
	"log"
	"math"
	"net"
	"net/http"
	neturl "net/url"
	"os"
	"path/filepath"
	"regexp"
	"runtime"
	"sort"
	"strconv"
	"strings"
	"syscall"
	"time"

	"github.com/caddyserver/caddy/v2"
	"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
	"github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
	"github.com/caddyserver/caddy/v2/modules/caddyhttp"
	"go.uber.org/zap"
	_ "modernc.org/sqlite"
)

//go:embed about.html list.html view.html
var templates embed.FS

type FormHandler struct {
	DBPath           string `json:"db_path,omitempty"`
	TemplatePath     string `json:"template_path,omitempty"`
	ListTemplatePath string `json:"list_template_path,omitempty"`
	ViewTemplatePath string `json:"view_template_path,omitempty"`
	TrustProxy       bool   `json:"trust_proxy,omitempty"`
	APIKey           string `json:"api_key,omitempty"`
	AllowCORS        bool   `json:"allow_cors,omitempty"`
	CORSOrigin       string `json:"cors_origin,omitempty"`
	MaxRequestMB     int    `json:"max_request_mb,omitempty"`
	MaxGIFFrames     int    `json:"max_gif_frames,omitempty"`
	MaxImageWorkers  int    `json:"max_image_workers,omitempty"`
	PathPrefix       string `json:"path_prefix,omitempty"`
	db               *sql.DB
	imageSemaphore   chan struct{}
	aboutHTML        []byte
	listHTML         []byte
	viewHTML         []byte
	viewTmpl         *template.Template
}

func (FormHandler) CaddyModule() caddy.ModuleInfo {
	return caddy.ModuleInfo{
		ID:  "http.handlers.form_handler",
		New: func() caddy.Module { return new(FormHandler) },
	}
}

func (h *FormHandler) Provision(ctx caddy.Context) error {
	if h.DBPath == "" {
		h.DBPath = filepath.Join(caddy.AppDataDir(), "form_handler", "form_data.db")
	}
	dataDir := filepath.Dir(h.DBPath)

	if err := os.MkdirAll(dataDir, 0750); err != nil {
		return fmt.Errorf("failed to create secure DB directory: %v", err)
	}

	// API Key 管理：从持久化文件读取或生成新的
	if h.APIKey == "" {
		apiKeyPath := filepath.Join(dataDir, ".api_key")
		if keyBytes, readErr := os.ReadFile(apiKeyPath); readErr == nil && len(keyBytes) > 0 {
			h.APIKey = string(keyBytes)
			caddy.Log().Named("formhandler").Info("Loaded existing API key from file")
		} else {
			newKey, err := generateCryptoString(32)
			if err != nil {
				return fmt.Errorf("failed to generate secure API key: %v", err)
			}
			h.APIKey = newKey
			if writeErr := os.WriteFile(apiKeyPath, []byte(h.APIKey), 0600); writeErr != nil {
				caddy.Log().Named("formhandler").Warn("Failed to persist API key to disk", zap.Error(writeErr))
			} else {
				maskedKey := "********"
				if len(h.APIKey) > 4 {
					maskedKey = "********" + h.APIKey[len(h.APIKey)-4:]
				}
				caddy.Log().Named("formhandler").Info("Auto-generated and persisted API key for form management (use this to access /list):",
					zap.String("api_key", maskedKey))
			}
		}
	}

	if h.MaxRequestMB <= 0 {
		h.MaxRequestMB = 50
	}
	if h.MaxGIFFrames <= 0 {
		h.MaxGIFFrames = 200
	}
	if h.MaxImageWorkers <= 0 {
		h.MaxImageWorkers = runtime.NumCPU()
	}

	h.imageSemaphore = make(chan struct{}, h.MaxImageWorkers)

	// 动态加载 about.html 模板
	var aboutHTML []byte
	var err error
	if h.TemplatePath != "" {
		aboutHTML, err = os.ReadFile(h.TemplatePath)
		if err != nil {
			return fmt.Errorf("failed to read custom about.html [%s]: %v", h.TemplatePath, err)
		}
	} else {
		aboutHTML, err = templates.ReadFile("about.html")
		if err != nil {
			return fmt.Errorf("failed to read embedded about.html: %v", err)
		}
	}

	if !bytes.Contains(aboutHTML, []byte("{{.CSRF_TOKEN}}")) {
		if h.TemplatePath != "" {
			return fmt.Errorf("custom template [%s] missing required {{.CSRF_TOKEN}} placeholder", h.TemplatePath)
		}
		return fmt.Errorf("embedded about.html missing required {{.CSRF_TOKEN}} placeholder")
	}
	h.aboutHTML = aboutHTML

	if h.ListTemplatePath != "" {
		h.listHTML, err = os.ReadFile(h.ListTemplatePath)
		if err != nil {
			return fmt.Errorf("failed to read custom list.html [%s]: %v", h.ListTemplatePath, err)
		}
	} else {
		h.listHTML, err = templates.ReadFile("list.html")
		if err != nil {
			return fmt.Errorf("failed to read embedded list.html: %v", err)
		}
	}

	if h.ViewTemplatePath != "" {
		h.viewHTML, err = os.ReadFile(h.ViewTemplatePath)
		if err != nil {
			return fmt.Errorf("failed to read custom view.html [%s]: %v", h.ViewTemplatePath, err)
		}
	} else {
		h.viewHTML, err = templates.ReadFile("view.html")
		if err != nil {
			return fmt.Errorf("failed to read embedded view.html: %v", err)
		}
	}

	funcMap := template.FuncMap{
		"hasSuffix": strings.HasSuffix,
	}
	h.viewTmpl, err = template.New("view").Funcs(funcMap).Parse(string(h.viewHTML))
	if err != nil {
		return fmt.Errorf("failed to parse view template: %v", err)
	}

	if h.PathPrefix != "" {
		h.PathPrefix = strings.TrimSuffix(h.PathPrefix, "/")
		if !strings.HasPrefix(h.PathPrefix, "/") {
			h.PathPrefix = "/" + h.PathPrefix
		}
		if h.ListTemplatePath == "" {
			h.listHTML = []byte(strings.Replace(string(h.listHTML), "const API_URL = '/api/data';",
				fmt.Sprintf("const API_URL = '%s/api/data';", h.PathPrefix), 1))
		}
		if h.TemplatePath == "" {
			h.aboutHTML = bytes.ReplaceAll(h.aboutHTML, []byte(`action="/about"`), []byte(fmt.Sprintf(`action="%s/about"`, h.PathPrefix)))
		}
	}

	var dberr error
	h.db, dberr = sql.Open("sqlite", h.DBPath)
	if dberr != nil {
		return dberr
	}

	numCPU := runtime.NumCPU()
	h.db.SetMaxOpenConns(numCPU + 2)
	h.db.SetMaxIdleConns(numCPU)
	h.db.SetConnMaxLifetime(1 * time.Hour)

	if _, err = h.db.Exec(`
		PRAGMA journal_mode = WAL;
		PRAGMA synchronous = NORMAL;
		PRAGMA busy_timeout = 10000;
		PRAGMA wal_autocheckpoint = 1000;
	`); err != nil {
		log.Printf("Warning: Failed to set SQLite pragmas: %v", err)
	}

	_, err = h.db.Exec(`CREATE TABLE IF NOT EXISTS form_data (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		form_path TEXT,
		payload TEXT,
		field_aliases TEXT,
		client_ip TEXT,
		access_token TEXT,
		token_expires_at DATETIME,
		submitted_at DATETIME DEFAULT CURRENT_TIMESTAMP
	);`)
	if err != nil {
		return err
	}

	h.db.Exec(`ALTER TABLE form_data ADD COLUMN IF NOT EXISTS client_ip TEXT`)
	h.db.Exec(`ALTER TABLE form_data ADD COLUMN IF NOT EXISTS access_token TEXT`)
	h.db.Exec(`ALTER TABLE form_data ADD COLUMN IF NOT EXISTS token_expires_at DATETIME`)
	h.db.Exec(`ALTER TABLE form_data ADD COLUMN IF NOT EXISTS field_aliases TEXT`)

	go h.startBackgroundGC(ctx, 12*time.Hour, 24*time.Hour)

	return nil
}

func generateCryptoString(length int) (string, error) {
	b := make([]byte, length)
	if _, err := rand.Read(b); err != nil {
		return "", err
	}
	return hex.EncodeToString(b), nil
}

func sanitizeFilename(name string) string {
	if strings.Contains(name, "..") {
		name = strings.ReplaceAll(name, "..", "_")
	}

	runes := []rune(name)
	if len(runes) > 100 {
		runes = runes[:100]
	}
	s := string(runes)

	return strings.Map(func(r rune) rune {
		if r < 32 || r == '/' || r == '\\' || r == '"' || r == '\'' || r == ':' || r == '|' || r == '?' || r == '*' {
			return '_'
		}
		return r
	}, s)
}

func getClientIP(r *http.Request, trustProxy bool) string {
	if trustProxy {
		if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
			ips := strings.Split(xff, ",")
			if len(ips) > 0 {
				return strings.TrimSpace(ips[0])
			}
		}
		if xri := r.Header.Get("X-Real-IP"); xri != "" {
			return xri
		}
	}
	host, _, _ := net.SplitHostPort(r.RemoteAddr)
	if host == "" {
		return r.RemoteAddr
	}
	return host
}

func setSecurityHeaders(w http.ResponseWriter, isHTTPS bool) {
	w.Header().Set("X-Content-Type-Options", "nosniff")
	w.Header().Set("X-Frame-Options", "DENY")
	if isHTTPS {
		w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
	}
	w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
	w.Header().Set("Content-Security-Policy",
		"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; object-src 'none'; frame-ancestors 'none'; base-uri 'self';")
}

func setCORSHeaders(w http.ResponseWriter, h *FormHandler, r *http.Request) {
	if !h.AllowCORS {
		return
	}
	origin := h.CORSOrigin
	if origin == "" {
		return
	}
	w.Header().Set("Access-Control-Allow-Origin", origin)
	w.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
	w.Header().Set("Access-Control-Max-Age", "86400")
	w.Header().Add("Vary", "Origin")
}

func (h *FormHandler) authenticateAPI(r *http.Request) bool {
	if h.APIKey == "" {
		return false
	}
	auth := r.Header.Get("Authorization")
	expectedBearer := "Bearer " + h.APIKey
	return subtle.ConstantTimeCompare([]byte(auth), []byte(h.APIKey)) == 1 ||
		subtle.ConstantTimeCompare([]byte(auth), []byte(expectedBearer)) == 1
}

func (h *FormHandler) handleAPIList(w http.ResponseWriter, r *http.Request) {
	setCORSHeaders(w, h, r)
	if r.Method == http.MethodOptions {
		w.WriteHeader(http.StatusOK)
		return
	}
	if !h.authenticateAPI(r) {
		w.Header().Set("WWW-Authenticate", `Bearer realm="FormHandler API"`)
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}

	pageStr := r.URL.Query().Get("page")
	sizeStr := r.URL.Query().Get("size")
	search := strings.TrimSpace(r.URL.Query().Get("search"))
	formPath := strings.TrimSpace(r.URL.Query().Get("form_path"))

	page, err := strconv.Atoi(pageStr)
	if err != nil || page < 1 {
		page = 1
	}
	size, err := strconv.Atoi(sizeStr)
	if err != nil || size < 1 {
		size = 10
	}
	if size > 100 {
		size = 100
	}
	offset := (page - 1) * size

	var whereConditions []string
	var whereArgs []interface{}
	if search != "" {
		escapedSearch := strings.ReplaceAll(strings.ReplaceAll(search, "%", "\\%"), "_", "\\_")
		whereConditions = append(whereConditions, "payload LIKE ? ESCAPE '\\'")
		whereArgs = append(whereArgs, "%"+escapedSearch+"%")
	}
	if formPath != "" {
		whereConditions = append(whereConditions, "form_path = ?")
		whereArgs = append(whereArgs, formPath)
	}

	whereClause := ""
	if len(whereConditions) > 0 {
		whereClause = " WHERE " + strings.Join(whereConditions, " AND ")
	}

	var totalCount int
	if whereClause != "" {
		countQuery := "SELECT COUNT(*) FROM form_data" + whereClause
		if err := h.db.QueryRow(countQuery, whereArgs...).Scan(&totalCount); err != nil {
			http.Error(w, "Failed to count records", http.StatusInternalServerError)
			return
		}
	} else {
		if err := h.db.QueryRow("SELECT COUNT(*) FROM form_data").Scan(&totalCount); err != nil {
			http.Error(w, "Failed to count records", http.StatusInternalServerError)
			return
		}
	}

	totalPages := int(math.Ceil(float64(totalCount) / float64(size)))
	if totalPages == 0 {
		totalPages = 1
	}

	selectQuery := "SELECT id, form_path, payload, field_aliases, client_ip, submitted_at FROM form_data" + whereClause + " ORDER BY submitted_at DESC LIMIT ? OFFSET ?"
	queryArgs := append(whereArgs, size, offset)
	rows, err := h.db.Query(selectQuery, queryArgs...)
	if err != nil {
		http.Error(w, "Failed to query data", http.StatusInternalServerError)
		return
	}
	defer rows.Close()

	type FormRecord struct {
		ID           int                    `json:"id"`
		FormPath     string                 `json:"form_path"`
		Data         map[string]interface{} `json:"data"`
		FieldAliases map[string]string      `json:"field_aliases"`
		ClientIP     string                 `json:"ip"`
		Submitted    string                 `json:"submitted_at"`
	}
	var data []FormRecord

	for rows.Next() {
		var item FormRecord
		var payloadJSON string
		var fieldAliasesJSON sql.NullString
		var clientIP sql.NullString
		if err := rows.Scan(&item.ID, &item.FormPath, &payloadJSON, &fieldAliasesJSON, &clientIP, &item.Submitted); err != nil {
			http.Error(w, "Failed to scan row", http.StatusInternalServerError)
			return
		}
		if err := json.Unmarshal([]byte(payloadJSON), &item.Data); err != nil {
			http.Error(w, "Failed to parse data", http.StatusInternalServerError)
			return
		}
		item.FieldAliases = make(map[string]string)
		if fieldAliasesJSON.Valid && fieldAliasesJSON.String != "" {
			if err := json.Unmarshal([]byte(fieldAliasesJSON.String), &item.FieldAliases); err != nil {
				log.Printf("[FormHandler] Failed to parse field_aliases: %v", err)
			}
		}
		if clientIP.Valid {
			item.ClientIP = clientIP.String
		} else {
			item.ClientIP = ""
		}
		data = append(data, item)
	}

	if err := rows.Err(); err != nil {
		log.Printf("[FormHandler] Row iteration error: %v", err)
	}

	result := map[string]interface{}{
		"data":       data,
		"page":       page,
		"totalPages": totalPages,
		"totalCount": totalCount,
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(result)
}

func (h *FormHandler) handleAPIDetail(w http.ResponseWriter, r *http.Request, id int) {
	setCORSHeaders(w, h, r)
	if r.Method == http.MethodOptions {
		w.WriteHeader(http.StatusOK)
		return
	}
	if !h.authenticateAPI(r) {
		w.Header().Set("WWW-Authenticate", `Bearer realm="FormHandler API"`)
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}

	var payloadJSON string
	var formPath string
	var clientIP sql.NullString
	var submitted string
	query := `SELECT form_path, payload, client_ip, submitted_at FROM form_data WHERE id = ?`
	err := h.db.QueryRow(query, id).Scan(&formPath, &payloadJSON, &clientIP, &submitted)
	if err == sql.ErrNoRows {
		http.Error(w, "Record not found", http.StatusNotFound)
		return
	}
	if err != nil {
		http.Error(w, "Failed to query data", http.StatusInternalServerError)
		return
	}

	var data map[string]interface{}
	if err := json.Unmarshal([]byte(payloadJSON), &data); err != nil {
		http.Error(w, "Failed to parse data", http.StatusInternalServerError)
		return
	}

	ipStr := ""
	if clientIP.Valid {
		ipStr = clientIP.String
	}

	result := map[string]interface{}{
		"id":           id,
		"form_path":    formPath,
		"data":         data,
		"ip":           ipStr,
		"submitted_at": submitted,
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(result)
}

func (h *FormHandler) handleAPIDelete(w http.ResponseWriter, r *http.Request, id int) {
	setCORSHeaders(w, h, r)
	if r.Method == http.MethodOptions {
		w.WriteHeader(http.StatusOK)
		return
	}
	if !h.authenticateAPI(r) {
		w.Header().Set("WWW-Authenticate", `Bearer realm="FormHandler API"`)
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}

	var payloadJSON string
	var formPath string
	query := `SELECT form_path, payload FROM form_data WHERE id = ?`
	err := h.db.QueryRow(query, id).Scan(&formPath, &payloadJSON)
	if err == sql.ErrNoRows {
		http.Error(w, "Record not found", http.StatusNotFound)
		return
	}
	if err != nil {
		http.Error(w, "Failed to query data", http.StatusInternalServerError)
		return
	}

	var data map[string]interface{}
	if err := json.Unmarshal([]byte(payloadJSON), &data); err == nil {
		h.cleanupOrphanFilesFromData(data)
	}

	result, err := h.db.Exec(`DELETE FROM form_data WHERE id = ?`, id)
	if err != nil {
		http.Error(w, "Failed to delete record", http.StatusInternalServerError)
		return
	}
	rowsAffected, _ := result.RowsAffected()
	if rowsAffected == 0 {
		http.Error(w, "Record not found", http.StatusNotFound)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

type ViewField struct {
	Label     string
	Key       string
	Value     string
	IsFile    bool
	FileURLs  []ViewFile
	ImageURLs []string
	HasImages bool
}

type ViewFile struct {
	Name    string
	URL     string
	Icon    template.HTML
	IsImage bool
}

type ViewData struct {
	Error            bool
	ErrorIcon        template.HTML
	ErrorTitle       string
	ErrorMessage     string
	Title            string
	Fields           []ViewField
	SubmittedAt      string
	ExpiresAt        string
	ExpiryWarning    bool
	ExpiryTime       string
	ShareTitle       string
	ShareDescription string
	ShareImage       string
	ShareURL         string

	ArticleTitle   string
	ArticleSummary string
	ArticleContent string
	ArticleImages  []string
	CoverImage     string
	AuthorName     string
	AuthorInitial  string
	OtherFields    []ViewField

	IconWarning template.HTML
	IconClock   template.HTML
	IconImage   template.HTML
	IconFile    template.HTML
	IconPdf     template.HTML
	IconText    template.HTML
	IconLock    template.HTML
	IconExpired template.HTML
}

func (h *FormHandler) handleView(w http.ResponseWriter, r *http.Request, token string) {
	isHTTPS := r.TLS != nil || (h.TrustProxy && r.Header.Get("X-Forwarded-Proto") == "https")
	setSecurityHeaders(w, isHTTPS)
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.Header().Set("Cache-Control", "private, max-age=60")

	data := ViewData{Title: "表单查看"}

	data.IconWarning = template.HTML(`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#f59e0b" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path><line x1="12" y1="9" x2="12" y2="13"></line><line x1="12" y1="17" x2="12.01" y2="17"></line></svg>`)
	data.IconClock = template.HTML(`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#f43f5e" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>`)
	data.IconImage = template.HTML(`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#3b82f6" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>`)
	data.IconFile = template.HTML(`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#64748b" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"></path><polyline points="14,2 14,8 20,8"></polyline></svg>`)
	data.IconPdf = template.HTML(`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"></path><polyline points="14,2 14,8 20,8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line></svg>`)
	data.IconText = template.HTML(`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#10b981" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"></path><polyline points="14,2 14,8 20,8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line><line x1="10" y1="9" x2="8" y2="9"></line></svg>`)
	data.IconLock = template.HTML(`<svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>`)
	data.IconExpired = template.HTML(`<svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="#f59e0b" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>`)

	var id int
	var formPath string
	var payloadJSON string
	var fieldAliasesJSON sql.NullString
	var tokenExpiresAtStr sql.NullString
	var submittedAtStr string
	var tokenExpiresAt time.Time

	query := `SELECT id, form_path, payload, field_aliases, token_expires_at, submitted_at FROM form_data WHERE access_token = ?`
	err := h.db.QueryRow(query, token).Scan(&id, &formPath, &payloadJSON, &fieldAliasesJSON, &tokenExpiresAtStr, &submittedAtStr)

	if err == sql.ErrNoRows {
		data.Error = true
		data.ErrorIcon = data.IconLock
		data.ErrorTitle = "链接无效"
		data.ErrorMessage = "此访问链接无效或已被删除"
		h.renderView(w, data)
		return
	}
	if err != nil {
		data.Error = true
		data.ErrorIcon = data.IconWarning
		data.ErrorTitle = "系统错误"
		data.ErrorMessage = "无法加载表单数据"
		h.renderView(w, data)
		return
	}

	if !tokenExpiresAtStr.Valid {
		submittedAt, err := time.Parse("2006-01-02 15:04:05", submittedAtStr)
		if err != nil {
			submittedAt = time.Now()
		}
		tokenExpiresAt = submittedAt.Add(48 * time.Hour)
	} else {
		// 【鲁棒性修复】清洗空格并支持多格式兼容解析
		rawTimeStr := strings.TrimSpace(tokenExpiresAtStr.String)
		var parseErr error
		timeLayouts := []string{
			"2006-01-02 15:04:05",
			"2006-01-02 15:04:05.999999999",
			time.RFC3339,
			"2006-01-02T15:04:05Z07:00",
		}
		for _, layout := range timeLayouts {
			tokenExpiresAt, parseErr = time.Parse(layout, rawTimeStr)
			if parseErr == nil {
				break
			}
		}

		if parseErr != nil {
			log.Printf("[FormHandler] 无法解析过期时间字符串: '%s', 错误: %v", tokenExpiresAtStr.String, parseErr)
			data.Error = true
			data.ErrorIcon = data.IconWarning
			data.ErrorTitle = "系统错误"
			data.ErrorMessage = "无法解析过期时间"
			h.renderView(w, data)
			return
		}
	}

	if time.Now().After(tokenExpiresAt) {
		data.Error = true
		data.ErrorIcon = data.IconExpired
		data.ErrorTitle = "链接已过期"
		data.ErrorMessage = "此访问链接已超过48小时有效期"
		h.renderView(w, data)
		return
	}

	timeUntilExpiry := tokenExpiresAt.Sub(time.Now())
	data.ExpiryWarning = timeUntilExpiry < 24*time.Hour
	if data.ExpiryWarning {
		if timeUntilExpiry < time.Hour {
			data.ExpiryTime = fmt.Sprintf("%.0f分钟", timeUntilExpiry.Minutes())
		} else {
			data.ExpiryTime = fmt.Sprintf("%.1f小时", timeUntilExpiry.Hours())
		}
	}

	var formPayload map[string]interface{}
	if err := json.Unmarshal([]byte(payloadJSON), &formPayload); err != nil {
		data.Error = true
		data.ErrorIcon = data.IconWarning
		data.ErrorTitle = "数据解析错误"
		data.ErrorMessage = "无法解析表单数据"
		h.renderView(w, data)
		return
	}

	data.SubmittedAt = formatDate(submittedAtStr)
	data.ExpiresAt = tokenExpiresAt.Format("2006-01-02 15:04:05")

	var templateAliases map[string]string
	if fieldAliasesJSON.Valid && fieldAliasesJSON.String != "" {
		if err := json.Unmarshal([]byte(fieldAliasesJSON.String), &templateAliases); err != nil {
			templateAliases = make(map[string]string)
		}
	} else {
		templateAliases = make(map[string]string)
	}

	builtInAliases := map[string]string{
		"name": "您的称呼", "username": "用户名", "nickname": "昵称",
		"email": "联系方式", "phone": "手机号", "mobile": "手机号", "telephone": "电话",
		"message": "反馈内容", "content": "内容", "comment": "留言", "feedback": "反馈",
		"title": "标题", "subject": "主题", "description": "描述", "remark": "备注", "note": "说明",
		"screenshot": "截图", "attachment": "附件", "file": "文件", "image": "图片", "photo": "照片", "avatar": "头像",
		"address": "地址", "location": "位置", "company": "公司", "organization": "单位",
		"website": "网站", "url": "网址", "link": "链接",
	}

	var fieldKeys []string
	for k := range formPayload {
		fieldKeys = append(fieldKeys, k)
	}
	sort.Strings(fieldKeys)

	data.Fields = make([]ViewField, 0)
	data.OtherFields = make([]ViewField, 0)
	data.ArticleImages = make([]string, 0)

	articleFieldMap := map[string]string{
		"title": "标题", "article_title": "标题", "文章标题": "标题", "headline": "标题",
		"summary": "摘要", "article_summary": "摘要", "文章摘要": "摘要", "description": "摘要",
		"content": "内容", "article_content": "内容", "文章内容": "内容", "body": "内容", "text": "内容",
		"cover": "封面", "cover_image": "封面", "封面图片": "封面", "article_image": "封面",
		"images": "图片", "article_images": "图片", "文章图片": "图片", "photos": "图片",
		"author": "作者", "article_author": "作者", "文章作者": "作者", "writer": "作者", "username": "作者", "name": "作者",
	}

	for _, key := range fieldKeys {
		value := formPayload[key]

		label := key
		if alias, ok := templateAliases[key]; ok && alias != "" {
			label = alias
		} else if alias, ok := builtInAliases[key]; ok {
			label = alias
		}

		field := ViewField{Label: label, Key: key}
		isArticleField := false

		if valueArr, ok := value.([]interface{}); ok && len(valueArr) > 0 {
			isFileField := true
			for _, v := range valueArr {
				if str, ok := v.(string); ok {
					if !strings.Contains(str, "/uploads/") {
						isFileField = false
						break
					}
				} else {
					isFileField = false
					break
				}
			}

			if isFileField {
				field.IsFile = true
				field.FileURLs = make([]ViewFile, 0)
				field.ImageURLs = make([]string, 0)

				for _, v := range valueArr {
					fileURL, _ := v.(string)
					safeURL := sanitizeUrl(fileURL)
					fileName := filepath.Base(safeURL)
					ext := strings.ToLower(filepath.Ext(fileName))

					isImage := ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".gif"
					icon := data.IconFile
					if isImage {
						icon = data.IconImage
						field.HasImages = true
						field.ImageURLs = append(field.ImageURLs, safeURL)

						lowerKey := strings.ToLower(key)
						if articleFieldMap[lowerKey] == "封面" && data.CoverImage == "" {
							data.CoverImage = safeURL
							isArticleField = true
						} else if articleFieldMap[lowerKey] == "图片" {
							data.ArticleImages = append(data.ArticleImages, safeURL)
							isArticleField = true
						}
					} else if ext == ".pdf" {
						icon = data.IconPdf
					} else if ext == ".txt" {
						icon = data.IconText
					}

					field.FileURLs = append(field.FileURLs, ViewFile{
						Name:    fileName,
						URL:     safeURL,
						Icon:    template.HTML(icon),
						IsImage: isImage,
					})
				}
			} else {
				strs := make([]string, 0)
				for _, v := range valueArr {
					strs = append(strs, fmt.Sprintf("%v", v))
				}
				field.Value = strings.Join(strs, ", ")
			}
		} else {
			field.Value = fmt.Sprintf("%v", value)

			lowerKey := strings.ToLower(key)
			switch articleFieldMap[lowerKey] {
			case "标题":
				if data.ArticleTitle == "" {
					data.ArticleTitle = field.Value
					isArticleField = true
				}
			case "摘要":
				if data.ArticleSummary == "" {
					data.ArticleSummary = field.Value
					isArticleField = true
				}
			case "内容":
				if data.ArticleContent == "" {
					data.ArticleContent = field.Value
					isArticleField = true
				}
			case "作者":
				if data.AuthorName == "" {
					data.AuthorName = field.Value
					isArticleField = true
				}
			}
		}

		if isArticleField {
			data.Fields = append(data.Fields, field)
		} else {
			data.OtherFields = append(data.OtherFields, field)
		}
	}

	if data.AuthorName == "" {
		data.AuthorName = "用户"
	}
	data.AuthorInitial = getInitial(data.AuthorName)

	if data.ArticleTitle == "" {
		data.ArticleTitle = "表单查看"
	}

	if data.ArticleContent != "" {
		data.ArticleContent = processImagePlaceholders(data.ArticleContent, data.CoverImage, data.ArticleImages)
	}

	data.ShareTitle = "表单数据 - " + data.SubmittedAt
	data.ShareDescription = "查看提交的表单内容"

	scheme := "http"
	if r.TLS != nil || (h.TrustProxy && r.Header.Get("X-Forwarded-Proto") == "https") {
		scheme = "https"
	}
	data.ShareURL = scheme + "://" + r.Host + r.URL.Path

	data.ShareImage = ""
	for _, field := range data.Fields {
		if len(field.ImageURLs) > 0 {
			imgPath := field.ImageURLs[0]
			if strings.HasPrefix(imgPath, "/") {
				data.ShareImage = scheme + "://" + r.Host + imgPath
			} else {
				data.ShareImage = imgPath
			}
			break
		}
	}

	h.renderView(w, data)
}

func (h *FormHandler) renderView(w http.ResponseWriter, data ViewData) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if err := h.viewTmpl.Execute(w, data); err != nil {
		http.Error(w, "模板执行错误: "+err.Error(), http.StatusInternalServerError)
		return
	}
}

func escapeHTML(s string) string {
	return template.HTMLEscapeString(s)
}

func getInitial(name string) string {
	if name == "" {
		return "?"
	}
	runes := []rune(name)
	if len(runes) > 0 {
		return string(runes[0])
	}
	return "?"
}


func processImagePlaceholders(content string, coverImage string, articleImages []string) string {
	log.Printf("[debug] input content=%q, articleImages len=%d", content, len(articleImages))

	// 正则：兼容标记内部无意空格 {{ image : all }}
	imagePattern := regexp.MustCompile(`\{\{\s*image\s*:\s*(cover|\d+|all)\s*(?:,\s*(\w+)\s*)?\s*\}\}`)
	matches := imagePattern.FindAllStringSubmatchIndex(content, -1)
	log.Printf("[debug] match count: %d", len(matches))

	// 从后向前替换，防止索引错乱
	for i := len(matches) - 1; i >= 0; i-- {
		match := matches[i]
		fullStart, fullEnd := match[0], match[1]
		idxStr := content[match[2]:match[3]]
		align := ""
		if match[4] != -1 {
			align = content[match[4]:match[5]]
		}

		var replacement string
		switch idxStr {
		case "all":
			if len(articleImages) > 0 {
				var sb strings.Builder
				sb.WriteString(`<div class="image-grid-layout">`)
				for j, img := range articleImages {
					sb.WriteString(fmt.Sprintf(`<img src="%s" alt="图片%d" class="grid-image">`, img, j+1))
				}
				sb.WriteString(`</div>`)
				replacement = sb.String()
			} else {
				// 没有图片：直接删掉标记
				replacement = ""
			}
		case "cover":
			if coverImage != "" {
				replacement = fmt.Sprintf(`<img src="%s" alt="封面图" class="article-cover-img">`, coverImage)
			} else {
				replacement = ""
			}
		default:
			idx, err := strconv.Atoi(idxStr)
			if err != nil || idx < 1 || idx > len(articleImages) {
				replacement = ""
			} else {
				imgSrc := articleImages[idx-1]
				var imgClass string
				switch align {
				case "left":
					imgClass = "article-image-float-left"
				case "right":
					imgClass = "article-image-float-right"
				case "center":
					imgClass = "article-image-center"
				default:
					imgClass = "article-image-inline"
				}
				replacement = fmt.Sprintf(`<img src="%s" alt="图片" class="%s">`, imgSrc, imgClass)
			}
		}
		// 切片原地替换
		content = content[:fullStart] + replacement + content[fullEnd:]
	}

	// 兜底：所有**仍然残留**的 {{ }} 转HTML实体，防止go‑template解析报错
	content = strings.ReplaceAll(content, "{{", `&#123;&#123;`)
	content = strings.ReplaceAll(content, "}}", `&#125;&#125;`)

	log.Printf("[debug] output content=%q", content)
	return content
}

func validateFileContent(file io.ReadSeeker) (string, error) {
	buf := make([]byte, 512)
	n, err := file.Read(buf)
	if err != nil && err != io.EOF {
		return "", fmt.Errorf("failed to read file header: %w", err)
	}
	if n == 0 {
		return "", fmt.Errorf("empty file")
	}

	mime := http.DetectContentType(buf[:n])
	if idx := strings.Index(mime, ";"); idx != -1 {
		mime = strings.TrimSpace(mime[:idx])
	}

	if _, err := file.Seek(0, io.SeekStart); err != nil {
		return "", err
	}

	allowedMimeTypes := map[string]bool{
		"image/jpeg":      true,
		"image/png":       true,
		"image/gif":       true,
		"application/pdf": true,
		"text/plain":      true,
	}
	if !allowedMimeTypes[mime] {
		return "", fmt.Errorf("disallowed file type: %s", mime)
	}
	return mime, nil
}

func formatDate(dateStr string) string {
	if t, err := time.Parse(time.RFC3339, dateStr); err == nil {
		return t.Format("2006-01-02 15:04:05")
	}
	if t, err := time.Parse("2006-01-02 15:04:05", dateStr); err == nil {
		return t.Format("2006-01-02 15:04:05")
	}
	if t, err := time.Parse("2006-01-02T15:04:05Z", dateStr); err == nil {
		return t.Format("2006-01-02 15:04:05")
	}
	return dateStr
}

func sanitizeUrl(u string) string {
	if u == "" {
		return "#"
	}
	if strings.HasPrefix(u, "/") {
		if strings.Contains(u, "/uploads/") {
			return u
		}
		return "#"
	}
	parsed, err := neturl.Parse(u)
	if err != nil {
		return "#"
	}
	if parsed.Scheme != "http" && parsed.Scheme != "https" {
		return "#"
	}
	return u
}

func (h *FormHandler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
	path := strings.TrimSuffix(r.URL.Path, "/")
	prefix := h.PathPrefix
	var effectivePath string

	if prefix != "" {
		if !strings.HasPrefix(path, prefix) {
			return next.ServeHTTP(w, r)
		}
		effectivePath = strings.TrimPrefix(path, prefix)
		if effectivePath == "" {
			effectivePath = "/"
		}
	} else {
		effectivePath = path
	}
	effectivePath = strings.TrimSuffix(effectivePath, "/")

	isHTTPS := r.TLS != nil || (h.TrustProxy && r.Header.Get("X-Forwarded-Proto") == "https")

	if effectivePath == "/list" || effectivePath == "/list.html" {
		setSecurityHeaders(w, isHTTPS)
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		w.Header().Set("Cache-Control", "no-store, max-age=0")
		w.Write(h.listHTML)
		return nil
	}

	if strings.HasPrefix(effectivePath, "/uploads/") {
		setSecurityHeaders(w, isHTTPS)
		fileName := filepath.Base(effectivePath)

		if fileName == "" || fileName == "." || fileName == ".." || strings.HasPrefix(fileName, "..") {
			http.Error(w, "Invalid filename", http.StatusBadRequest)
			return nil
		}

		uploadDir := filepath.Join(filepath.Dir(h.DBPath), "uploads")
		filePath := filepath.Join(uploadDir, fileName)
		cleanFilePath := filepath.Clean(filePath)
		cleanUploadDir := filepath.Clean(uploadDir)
		if !strings.HasPrefix(cleanFilePath, cleanUploadDir+string(filepath.Separator)) {
			http.Error(w, "Access denied", http.StatusForbidden)
			return nil
		}

		preLstat, err := os.Lstat(filePath)
		if err != nil {
			http.NotFound(w, r)
			return nil
		}
		if preLstat.Mode()&os.ModeSymlink != 0 || preLstat.IsDir() {
			http.Error(w, "Access denied", http.StatusForbidden)
			return nil
		}

		file, err := safeOpenFileNoFollow(filePath)
		if err != nil {
			http.NotFound(w, r)
			return nil
		}
		defer file.Close()

		fstatInfo, err := file.Stat()
		if err != nil {
			http.NotFound(w, r)
			return nil
		}

		postLstat, err := os.Lstat(filePath)
		if err != nil {
			http.NotFound(w, r)
			return nil
		}
		if postLstat.Mode()&os.ModeSymlink != 0 {
			http.Error(w, "Access denied", http.StatusForbidden)
			return nil
		}
		if !os.SameFile(postLstat, fstatInfo) {
			http.Error(w, "Access denied", http.StatusForbidden)
			return nil
		}

		if !fstatInfo.Mode().IsRegular() {
			http.Error(w, "Access denied", http.StatusForbidden)
			return nil
		}

		http.ServeContent(w, r, fileName, fstatInfo.ModTime(), file)
		return nil
	}

	if strings.HasPrefix(effectivePath, "/view/") {
		token := strings.TrimPrefix(effectivePath, "/view/")
		h.handleView(w, r, token)
		return nil
	}

	if effectivePath == "/api/data" || strings.HasPrefix(effectivePath, "/api/data/") {
		setSecurityHeaders(w, isHTTPS)
		if r.Method == http.MethodOptions {
			setCORSHeaders(w, h, r)
			w.WriteHeader(http.StatusOK)
			return nil
		}
		if effectivePath == "/api/data" && r.Method == http.MethodGet {
			h.handleAPIList(w, r)
			return nil
		}
		if strings.HasPrefix(effectivePath, "/api/data/") {
			idStr := strings.TrimPrefix(effectivePath, "/api/data/")
			id, err := strconv.Atoi(idStr)
			if err != nil {
				http.Error(w, "Invalid ID", http.StatusBadRequest)
				return nil
			}
			if r.Method == http.MethodGet {
				h.handleAPIDetail(w, r, id)
				return nil
			}
			if r.Method == http.MethodDelete {
				h.handleAPIDelete(w, r, id)
				return nil
			}
		}
		http.Error(w, "Not found", http.StatusNotFound)
		return nil
	}

	fileExt := filepath.Ext(effectivePath)
	if fileExt != "" && !strings.HasPrefix(effectivePath, "/uploads/") {
		return next.ServeHTTP(w, r)
	}

	if r.Method == http.MethodGet {
		setSecurityHeaders(w, isHTTPS)
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		w.Header().Set("Cache-Control", "no-store, max-age=0")

		var csrfToken string
		cookie, err := r.Cookie("csrf_token")
		if err == nil && cookie.Value != "" && len(cookie.Value) >= 16 {
			csrfToken = cookie.Value
		} else {
			csrfToken, err = generateCryptoString(16)
			if err != nil {
				http.Error(w, "Internal Server Error", http.StatusInternalServerError)
				return nil
			}
		}

		cookiePath := "/"
		if prefix != "" {
			cookiePath = prefix
		}
		http.SetCookie(w, &http.Cookie{
			Name:     "csrf_token",
			Value:    csrfToken,
			Path:     cookiePath,
			HttpOnly: true,
			SameSite: http.SameSiteLaxMode,
			Secure:   isHTTPS,
			MaxAge:   3600,
		})

		csrfInput := fmt.Sprintf(`<input type="hidden" name="csrf_token" value="%s">`, csrfToken)
		rendered := bytes.ReplaceAll(h.aboutHTML, []byte("{{.CSRF_TOKEN}}"), []byte(csrfInput))
		w.Write(rendered)
		return nil
	}

	if r.Method == http.MethodPost {
		setSecurityHeaders(w, isHTTPS)
		w.Header().Set("Content-Type", "application/json")

		maxBytes := int64(h.MaxRequestMB) << 20
		r.Body = http.MaxBytesReader(w, r.Body, maxBytes)

		if err := r.ParseMultipartForm(maxBytes); err != nil {
			w.WriteHeader(http.StatusBadRequest)
			json.NewEncoder(w).Encode(map[string]string{"error": "Failed to parse form"})
			return nil
		}
		defer r.MultipartForm.RemoveAll()

		originValid := true
		origin := r.Header.Get("Origin")
		referer := r.Header.Get("Referer")

		expectedScheme := "http"
		if isHTTPS {
			expectedScheme = "https"
		}
		expectedOrigin := expectedScheme + "://" + r.Host

		if origin != "" {
			if origin != expectedOrigin {
				originValid = false
			}
		} else if referer != "" {
			if !strings.HasPrefix(referer, expectedOrigin+"/") && referer != expectedOrigin {
				originValid = false
			}
		}

		if !originValid {
			w.WriteHeader(http.StatusForbidden)
			json.NewEncoder(w).Encode(map[string]string{"error": "Invalid origin"})
			return nil
		}

		cookie, err := r.Cookie("csrf_token")
		csrfTokenFromForm := ""
		if len(r.MultipartForm.Value["csrf_token"]) > 0 {
			csrfTokenFromForm = r.MultipartForm.Value["csrf_token"][0]
		}
		if err != nil || csrfTokenFromForm == "" || cookie.Value != csrfTokenFromForm {
			w.WriteHeader(http.StatusForbidden)
			json.NewEncoder(w).Encode(map[string]string{"error": "CSRF validation failed"})
			return nil
		}
		delete(r.MultipartForm.Value, "csrf_token")

		var fieldAliasesJSON string
		if len(r.MultipartForm.Value["_field_aliases"]) > 0 {
			fieldAliasesJSON = r.MultipartForm.Value["_field_aliases"][0]
		}

		allFormData := make(map[string]interface{})
		fieldCount := 0
		const maxFields = 100
		const maxFieldLength = 10000

		for key, values := range r.MultipartForm.Value {
			if key == "_field_aliases" {
				continue
			}
			fieldCount++
			if fieldCount > maxFields {
				continue
			}

			var safeValues []string
			for _, v := range values {
				if len(v) > maxFieldLength {
					safeValues = append(safeValues, v[:maxFieldLength])
				} else {
					safeValues = append(safeValues, v)
				}
			}
			allFormData[key] = safeValues
		}

		uploadDir := filepath.Join(filepath.Dir(h.DBPath), "uploads")
		if err := os.MkdirAll(uploadDir, 0750); err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			json.NewEncoder(w).Encode(map[string]string{"error": "Server filesystem error"})
			return nil
		}

		allowedMimeToExt := map[string]string{
			"image/jpeg":      ".jpg",
			"image/png":       ".png",
			"image/gif":       ".gif",
			"application/pdf": ".pdf",
			"text/plain":      ".txt",
		}

		var trackedSavedFiles []string
		var processErrors []string
		fileCount := 0

		for fieldName, fileHeaders := range r.MultipartForm.File {
			var filePaths []string

			for _, fileHeader := range fileHeaders {
				fileCount++
				safeNameStr := sanitizeFilename(fileHeader.Filename)

				if strings.Contains(safeNameStr, "..") || strings.Contains(fileHeader.Filename, "..") {
					processErrors = append(processErrors, fmt.Sprintf("%s: Invalid filename", safeNameStr))
					continue
				}

				if fileCount > 10 {
					processErrors = append(processErrors, fmt.Sprintf("%s: Exceeded maximum file count", safeNameStr))
					continue
				}

				var finalSavedPath string
				processingErr := func() error {
					select {
					case <-r.Context().Done():
						return r.Context().Err()
					default:
					}

					file, err := fileHeader.Open()
					if err != nil {
						return fmt.Errorf("failed to open file: %w", err)
					}
					defer file.Close()

					realMimeType, err := validateFileContent(file)
					if err != nil {
						return fmt.Errorf("file validation failed: %w", err)
					}

					_, allowed := allowedMimeToExt[realMimeType]
					if !allowed {
						return fmt.Errorf("unsupported MIME type: %s", realMimeType)
					}

					tempFile, err := os.CreateTemp(uploadDir, "tmp-*.part")
					if err != nil {
						return fmt.Errorf("failed to create temp file: %w", err)
					}
					tempName := tempFile.Name()

					var fileSaved bool
					defer func() {
						if !fileSaved {
							os.Remove(tempName)
						}
					}()

					isImage := realMimeType == "image/gif" || realMimeType == "image/jpeg" || realMimeType == "image/png"
					if isImage {
						select {
						case h.imageSemaphore <- struct{}{}:
						case <-r.Context().Done():
							return r.Context().Err()
						}
						defer func() { <-h.imageSemaphore }()
					}

					if realMimeType == "image/gif" {
						const maxGifSize = 50 * 1024 * 1024
						if _, err := file.Seek(0, io.SeekStart); err != nil {
							return fmt.Errorf("file reset failed: %w", err)
						}

						limitedFile := io.LimitReader(file, maxGifSize+1)
						gifImg, err := gif.DecodeAll(limitedFile)
						if err != nil {
							return fmt.Errorf("failed to decode GIF: %w", err)
						}
						if len(gifImg.Image) > h.MaxGIFFrames {
							return fmt.Errorf("GIF file exceeds maximum frame count (%d > %d)", len(gifImg.Image), h.MaxGIFFrames)
						}

						var totalPixels int64 = 0
						for _, frame := range gifImg.Image {
							width := frame.Bounds().Dx()
							height := frame.Bounds().Dy()
							if width > 4096 || height > 4096 {
								return fmt.Errorf("GIF frame size exceeds 4096x4096 limit")
							}
							totalPixels += int64(width) * int64(height)
							if totalPixels > 16*1024*1024 {
								return fmt.Errorf("GIF exceeds total pixel limit")
							}
						}
						if err := gif.EncodeAll(tempFile, gifImg); err != nil {
							return fmt.Errorf("failed to re-encode GIF: %w", err)
						}
					} else if realMimeType == "image/jpeg" || realMimeType == "image/png" {
						cfg, _, err := image.DecodeConfig(file)
						if err != nil {
							return fmt.Errorf("invalid image metadata")
						}

						if cfg.Width > 4096 || cfg.Height > 4096 {
							return fmt.Errorf("image size exceeds 4096x4096 limit")
						}
						if int64(cfg.Width)*int64(cfg.Height) > 16*1024*1024 {
							return fmt.Errorf("image exceeds total pixel limit (16MP)")
						}

						if _, err := file.Seek(0, io.SeekStart); err != nil {
							return fmt.Errorf("file stream error after config check: %w", err)
						}

						const maxImageSize = 50 * 1024 * 1024
						limitedFile := io.LimitReader(file, maxImageSize+1)
						img, format, err := image.Decode(limitedFile)
						if err != nil {
							return fmt.Errorf("malformed image payload")
						}
						switch format {
						case "jpeg":
							err = jpeg.Encode(tempFile, img, &jpeg.Options{Quality: 90})
						case "png":
							err = png.Encode(tempFile, img)
						default:
							err = fmt.Errorf("unexpected internal format")
						}
						if err != nil {
							return fmt.Errorf("image encoding failed")
						}
					} else {
						if _, err := io.Copy(tempFile, file); err != nil {
							return fmt.Errorf("failed to save file: %w", err)
						}
					}

					if err := tempFile.Close(); err != nil {
						return fmt.Errorf("failed to close temp file: %w", err)
					}

					randomStr, err := generateCryptoString(16)
					if err != nil {
						return fmt.Errorf("failed to generate random string: %w", err)
					}
					finalSavedPath = filepath.Join(uploadDir, randomStr+"-"+safeNameStr+allowedMimeToExt[realMimeType])
					if err := os.Rename(tempName, finalSavedPath); err != nil {
						return fmt.Errorf("failed to rename temp file: %w", err)
					}
					fileSaved = true
					return nil
				}()

				if processingErr != nil {
					if processingErr == context.Canceled {
						h.cleanupOrphanFiles(trackedSavedFiles)
						return nil
					}
					processErrors = append(processErrors, fmt.Sprintf("%s: %v", safeNameStr, processingErr))
				} else if finalSavedPath != "" {
					fileURL := h.PathPrefix + "/uploads/" + filepath.Base(finalSavedPath)
					filePaths = append(filePaths, fileURL)
					trackedSavedFiles = append(trackedSavedFiles, finalSavedPath)
				}
			}

			if len(filePaths) > 0 {
				allFormData[fieldName] = filePaths
			}
		}

		jsonData, err := json.Marshal(allFormData)
		if err != nil || string(jsonData) == "{}" {
			h.cleanupOrphanFiles(trackedSavedFiles)
			w.WriteHeader(http.StatusBadRequest)
			json.NewEncoder(w).Encode(map[string]interface{}{
				"error":    "Empty or invalid form submission",
				"warnings": processErrors,
			})
			return nil
		}

		accessToken, err := generateCryptoString(32)
		if err != nil {
			h.cleanupOrphanFiles(trackedSavedFiles)
			w.WriteHeader(http.StatusInternalServerError)
			json.NewEncoder(w).Encode(map[string]interface{}{"error": "Failed to generate access token"})
			return nil
		}

		tokenExpiresAt := time.Now().Add(48 * time.Hour)
		clientIP := getClientIP(r, h.TrustProxy)

		tx, err := h.db.Begin()
		if err != nil {
			h.cleanupOrphanFiles(trackedSavedFiles)
			w.WriteHeader(http.StatusInternalServerError)
			json.NewEncoder(w).Encode(map[string]interface{}{"error": "Database transaction failed"})
			return nil
		}
		defer tx.Rollback()

		_, err = tx.Exec(`INSERT INTO form_data (form_path, payload, field_aliases, client_ip, access_token, token_expires_at) VALUES (?, ?, ?, ?, ?, ?)`,
			effectivePath, string(jsonData), fieldAliasesJSON, clientIP, accessToken, tokenExpiresAt.Format("2006-01-02 15:04:05"))
		if err != nil {
			h.cleanupOrphanFiles(trackedSavedFiles)
			w.WriteHeader(http.StatusInternalServerError)
			json.NewEncoder(w).Encode(map[string]interface{}{"error": "Data insertion failed"})
			return nil
		}

		if err := tx.Commit(); err != nil {
			h.cleanupOrphanFiles(trackedSavedFiles)
			w.WriteHeader(http.StatusInternalServerError)
			json.NewEncoder(w).Encode(map[string]interface{}{"error": "Database commit failed"})
			return nil
		}

		scheme := "http"
		if r.TLS != nil || (h.TrustProxy && r.Header.Get("X-Forwarded-Proto") == "https") {
			scheme = "https"
		}
		viewURL := fmt.Sprintf("%s://%s%s/view/%s", scheme, r.Host, prefix, accessToken)

		response := map[string]interface{}{
			"status":     "success",
			"view_url":   viewURL,
			"token":      accessToken,
			"expires_at": tokenExpiresAt.Format(time.RFC3339),
		}
		if len(processErrors) > 0 {
			response["status"] = "partial_success"
			response["warnings"] = processErrors
		}

		w.WriteHeader(http.StatusOK)
		json.NewEncoder(w).Encode(response)
		return nil
	}

	return next.ServeHTTP(w, r)
}

func (h *FormHandler) cleanupOrphanFiles(paths []string) {
	for _, p := range paths {
		os.Remove(p)
	}
}

func (h *FormHandler) cleanupOrphanFilesFromData(data map[string]interface{}) {
	uploadDir := filepath.Join(filepath.Dir(h.DBPath), "uploads")
	for _, val := range data {
		if arr, ok := val.([]interface{}); ok {
			for _, item := range arr {
				if str, ok := item.(string); ok && strings.Contains(str, "/uploads/") {
					fullPath := filepath.Join(uploadDir, filepath.Base(str))
					if err := os.Remove(fullPath); err != nil && !os.IsNotExist(err) {
						log.Printf("[FormHandler GC] GC: Failed to remove file %s: %v", fullPath, err)
					}
				}
			}
		}
	}
}

func (h *FormHandler) startBackgroundGC(ctx context.Context, interval time.Duration, maxAge time.Duration) {
	timer := time.NewTimer(5 * time.Minute)
	defer timer.Stop()
	select {
	case <-timer.C:
	case <-ctx.Done():
		return
	}
	h.runGC(maxAge)

	ticker := time.NewTicker(interval)
	defer ticker.Stop()
	for {
		select {
		case <-ticker.C:
			h.runGC(maxAge)
		case <-ctx.Done():
			return
		}
	}
}

func (h *FormHandler) runGC(maxAge time.Duration) {
	if h.db == nil {
		return
	}

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	cutoff := time.Now().Add(-maxAge).Format("2006-01-02 15:04:05")
	query := `SELECT id, payload FROM form_data WHERE token_expires_at < ? OR token_expires_at IS NULL`
	rows, err := h.db.QueryContext(ctx, query, cutoff)
	if err != nil {
		return
	}
	defer rows.Close()

	var ids []int
	for rows.Next() {
		var id int
		var payloadJSON string
		if err := rows.Scan(&id, &payloadJSON); err != nil {
			continue
		}
		var payload map[string]interface{}
		if err := json.Unmarshal([]byte(payloadJSON), &payload); err == nil {
			h.cleanupOrphanFilesFromData(payload)
		}
		ids = append(ids, id)
	}

	if len(ids) > 0 {
		placeholders := strings.Repeat("?,", len(ids))
		placeholders = placeholders[:len(placeholders)-1]
		query := fmt.Sprintf(`DELETE FROM form_data WHERE id IN (%s)`, placeholders)
		args := make([]interface{}, len(ids))
		for i, v := range ids {
			args[i] = v
		}
		h.db.Exec(query, args...)
	}

	h.cleanupOrphanUploads()
}

func (h *FormHandler) cleanupOrphanUploads() {
	uploadDir := filepath.Join(filepath.Dir(h.DBPath), "uploads")
	files, err := os.ReadDir(uploadDir)
	if err != nil {
		return
	}

	rows, err := h.db.Query(`SELECT payload FROM form_data`)
	if err != nil {
		return
	}
	defer rows.Close()

	fileNameSet := make(map[string]bool)
	for rows.Next() {
		var payloadJSON string
		if err := rows.Scan(&payloadJSON); err != nil {
			continue
		}
		var payload map[string]interface{}
		if err := json.Unmarshal([]byte(payloadJSON), &payload); err == nil {
			for _, value := range payload {
				if valueArr, ok := value.([]interface{}); ok {
					for _, v := range valueArr {
						if filePath, ok := v.(string); ok && strings.Contains(filePath, "/uploads/") {
							fileNameSet[filepath.Base(filePath)] = true
						}
					}
				}
			}
		}
	}

	cutoffTime := time.Now().Add(-24 * time.Hour)
	for _, file := range files {
		if file.IsDir() {
			continue
		}
		fileName := file.Name()
		isTempFile := strings.HasPrefix(fileName, "tmp-") || strings.HasSuffix(fileName, ".part")

		if isTempFile {
			info, err := file.Info()
			if err == nil && info.ModTime().Before(cutoffTime) {
				os.Remove(filepath.Join(uploadDir, fileName))
				continue
			}
		}

		if !fileNameSet[fileName] {
			os.Remove(filepath.Join(uploadDir, fileName))
		}
	}
}

func (h *FormHandler) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
	for d.Next() {
		for d.NextBlock(0) {
			switch d.Val() {
			case "db_path":
				if !d.NextArg() {
					return d.ArgErr()
				}
				h.DBPath = d.Val()
			case "template":
				if !d.NextArg() {
					return d.ArgErr()
				}
				h.TemplatePath = d.Val()
			case "list_template":
				if !d.NextArg() {
					return d.ArgErr()
				}
				h.ListTemplatePath = d.Val()
			case "view_template":
				if !d.NextArg() {
					return d.ArgErr()
				}
				h.ViewTemplatePath = d.Val()
			case "trust_proxy":
				if !d.NextArg() {
					h.TrustProxy = false
				} else {
					val := strings.ToLower(d.Val())
					h.TrustProxy = val == "true" || val == "on" || val == "1"
				}
			case "api_key":
				if !d.NextArg() {
					return d.ArgErr()
				}
				h.APIKey = d.Val()
			case "allow_cors":
				if !d.NextArg() {
					h.AllowCORS = false
				} else {
					val := strings.ToLower(d.Val())
					h.AllowCORS = val == "true" || val == "on" || val == "1"
				}
			case "cors_origin":
				if !d.NextArg() {
					return d.ArgErr()
				}
				h.CORSOrigin = d.Val()
			case "max_request_mb":
				if !d.NextArg() {
					return d.ArgErr()
				}
				mb, err := strconv.Atoi(d.Val())
				if err != nil {
					return d.Errf("invalid max_request_mb: %v", err)
				}
				h.MaxRequestMB = mb
			case "max_gif_frames":
				if !d.NextArg() {
					return d.ArgErr()
				}
				frames, err := strconv.Atoi(d.Val())
				if err != nil {
					return d.Errf("invalid max_gif_frames: %v", err)
				}
				h.MaxGIFFrames = frames
			case "max_image_workers":
				if !d.NextArg() {
					return d.ArgErr()
				}
				workers, err := strconv.Atoi(d.Val())
				if err != nil {
					return d.Errf("invalid max_image_workers: %v", err)
				}
				h.MaxImageWorkers = workers
			case "path_prefix":
				if !d.NextArg() {
					return d.ArgErr()
				}
				h.PathPrefix = d.Val()
			default:
				return d.Errf("unrecognized subdirective: %s", d.Val())
			}
		}
	}
	return nil
}

func safeOpenFileNoFollow(path string) (*os.File, error) {
	if runtime.GOOS == "windows" {
		return os.Open(path)
	}
	fd, err := syscall.Open(path, syscall.O_RDONLY|syscall.O_NOFOLLOW, 0)
	if err != nil {
		return nil, err
	}
	return os.NewFile(uintptr(fd), path), nil
}

func init() {
	caddy.RegisterModule(&FormHandler{})
	httpcaddyfile.RegisterHandlerDirective("form_handler", parseFormHandler)
}

func parseFormHandler(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
	fh := new(FormHandler)
	err := fh.UnmarshalCaddyfile(h.Dispenser)
	return fh, err
}

func (h *FormHandler) Cleanup() error {
	if h.db != nil {
		return h.db.Close()
	}
	return nil
}

var (
	_ caddy.Provisioner           = (*FormHandler)(nil)
	_ caddyhttp.MiddlewareHandler = (*FormHandler)(nil)
	_ caddyfile.Unmarshaler       = (*FormHandler)(nil)
	_ caddy.CleanerUpper          = (*FormHandler)(nil)
)
