package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strings"
)

func createSimulation(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")
	if r.Method == "OPTIONS" {
		w.Header().Set("Access-Control-Allow-Methods", "POST")
		w.WriteHeader(http.StatusOK)
		return
	}

	if r.Method != "POST" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	bodyBytes, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "Failed to read request body", http.StatusBadRequest)
		return
	}
	defer r.Body.Close()
	configStr := string(bodyBytes)

	if configStr == "" {
		http.Error(w, "Config cannot be empty", http.StatusBadRequest)
		return
	}

	// Pattern validation: must contain a search pattern (spiral, lawnmower, or levy)
	hasPattern := false
	
	// Fast regex check or parse to detect patterns
	var jsonParsed map[string]interface{}
	err = json.Unmarshal(bodyBytes, &jsonParsed)
	if err != nil {
		http.Error(w, "Invalid configuration format: must be valid JSON", http.StatusBadRequest)
		return
	}

	// Valid JSON, traverse and look for pattern
	for k, v := range jsonParsed {
		if k == "search.yaml" || k == "search" {
			if searchMap, ok := v.(map[string]interface{}); ok {
				if _, ok := searchMap["spiral"]; ok { hasPattern = true }
				if _, ok := searchMap["lawnmower"]; ok { hasPattern = true }
				if _, ok := searchMap["levy"]; ok { hasPattern = true }
			}
		}
	}

	if !hasPattern {
		http.Error(w, "Simulation configuration must include a search pattern (spiral, lawnmower, or levy)", http.StatusBadRequest)
		return
	}

	// Check if this config already exists
	var existingID int
	var existingName string
	err = db.QueryRow("SELECT id, name FROM simulations WHERE config = ?", configStr).Scan(&existingID, &existingName)
	if err == nil {
		// Found exact config, return the existing run info
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(map[string]interface{}{
			"id":   existingID,
			"name": existingName,
		})
		return
	}

	var count int
	db.QueryRow("SELECT COUNT(*) FROM simulations").Scan(&count)
	newName := fmt.Sprintf("simulation_%d", count+1)

	// ensure name doesn't exist
	for {
		var temp int
		err := db.QueryRow("SELECT id FROM simulations WHERE name = ?", newName).Scan(&temp)
		if err == sql.ErrNoRows {
			break
		}
		count++
		newName = fmt.Sprintf("simulation_%d", count+1)
	}

	res, err := db.Exec("INSERT INTO simulations(name, config) VALUES(?, ?)", newName, configStr)
	if err != nil {
		log.Println("Insert simulation error:", err)
		http.Error(w, "Failed to create", http.StatusInternalServerError)
		return
	}
	newID, _ := res.LastInsertId()

	// Ensure the directory exists
	resultsDir := filepath.Join("../results", newName)
	os.MkdirAll(resultsDir, 0755)

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]interface{}{
		"id":   newID,
		"name": newName,
	})
}

func getSimulations(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")
	if r.Method == "OPTIONS" {
		w.Header().Set("Access-Control-Allow-Methods", "GET")
		w.WriteHeader(http.StatusOK)
		return
	}

	rows, err := db.Query("SELECT id, name, config, created_at, search_time, total_time FROM simulations")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer rows.Close()

	var sims []Simulation
	for rows.Next() {
		var s Simulation
		err = rows.Scan(&s.ID, &s.Name, &s.Config, &s.CreatedAt, &s.SearchTime, &s.TotalTime)
		if err != nil {
			log.Println("Row scan error:", err)
			continue
		}
		sims = append(sims, s)
	}

	if sims == nil {
		sims = []Simulation{}
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(sims)
}

func getSimulationDetails(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")
	if r.Method == "OPTIONS" {
		w.Header().Set("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS")
		w.WriteHeader(http.StatusOK)
		return
	}

	pathParts := strings.Split(strings.Trim(r.URL.Path[len("/api/simulations/"):], "/"), "/")
	idStr := pathParts[0]

	if idStr == "" || idStr == "create" {
		http.Error(w, "Not found", http.StatusNotFound)
		return
	}

	if r.Method == "PUT" && len(pathParts) > 1 && pathParts[1] == "time" {
		updateSimulationTime(w, r, idStr)
		return
	}

	if r.Method == "POST" && len(pathParts) > 1 && pathParts[1] == "upload" {
		uploadSimulationResource(w, r, idStr)
		return
	}

	if r.Method == "PUT" && len(pathParts) > 1 && pathParts[1] == "rename" {
		renameSimulation(w, r, idStr)
		return
	}

	if r.Method == "DELETE" && len(pathParts) == 1 {
		deleteSimulation(w, r, idStr)
		return
	}

	if r.Method != "GET" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	var s Simulation
	err := db.QueryRow("SELECT id, name, config, created_at, search_time, total_time FROM simulations WHERE id = ?", idStr).Scan(&s.ID, &s.Name, &s.Config, &s.CreatedAt, &s.SearchTime, &s.TotalTime)
	if err != nil {
		if err == sql.ErrNoRows {
			http.Error(w, "Simulation not found", http.StatusNotFound)
		} else {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
		return
	}

	rows, err := db.Query("SELECT filename FROM resources WHERE simulation_id = ?", s.ID)
	if err == nil {
		defer rows.Close()
		for rows.Next() {
			var fname string
			if err := rows.Scan(&fname); err == nil {
				s.Resources = append(s.Resources, fname)
				if stat, err := os.Stat(filepath.Join("../results", s.Name, fname)); err == nil {
					s.TotalSizeBytes += stat.Size()
				}
			}
		}
	}
	if s.Resources == nil {
		s.Resources = []string{}
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(s)
}

func updateSimulationTime(w http.ResponseWriter, r *http.Request, idStr string) {
	var reqBody struct {
		SearchTime *float64 `json:"search_time"`
		TotalTime  *float64 `json:"total_time"`
	}

	err := json.NewDecoder(r.Body).Decode(&reqBody)
	if err != nil {
		http.Error(w, "Invalid request body", http.StatusBadRequest)
		return
	}
	defer r.Body.Close()

	if reqBody.SearchTime == nil || reqBody.TotalTime == nil {
		http.Error(w, "Missing search_time or total_time", http.StatusBadRequest)
		return
	}

	_, err = db.Exec("UPDATE simulations SET search_time = ?, total_time = ? WHERE id = ?", *reqBody.SearchTime, *reqBody.TotalTime, idStr)
	if err != nil {
		log.Println("Update simulation error:", err)
		http.Error(w, "Failed to update", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]string{"status": "success"})
}

func deleteSimulation(w http.ResponseWriter, r *http.Request, idStr string) {
	var name string
	err := db.QueryRow("SELECT name FROM simulations WHERE id = ?", idStr).Scan(&name)
	if err != nil {
		if err == sql.ErrNoRows {
			http.Error(w, "Simulation not found", http.StatusNotFound)
		} else {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
		return
	}

	// Attempt dropping resource map hooks first
	_, err = db.Exec("DELETE FROM resources WHERE simulation_id = ?", idStr)
	if err != nil {
		log.Println("Warning: Error deleting resources map from DB:", err)
	}
	
	_, err = db.Exec("DELETE FROM simulations WHERE id = ?", idStr)
	if err != nil {
		log.Println("Error deleting simulation from DB:", err)
		http.Error(w, "Failed to delete from database", http.StatusInternalServerError)
		return
	}

	// Physically destroy data payload mapped onto it 
	dirPath := filepath.Join("../results", name)
	if _, statErr := os.Stat(dirPath); statErr == nil {
		err = os.RemoveAll(dirPath)
		if err != nil {
			log.Println("Warning: Failed fully deleting physical directory items:", err)
		}
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]string{"status": "success"})
}

func renameSimulation(w http.ResponseWriter, r *http.Request, idStr string) {
	var reqBody struct {
		Name string `json:"name"`
	}

	err := json.NewDecoder(r.Body).Decode(&reqBody)
	if err != nil || strings.TrimSpace(reqBody.Name) == "" {
		http.Error(w, "Invalid request body or missing name", http.StatusBadRequest)
		return
	}
	defer r.Body.Close()

	newName := strings.TrimSpace(reqBody.Name)

	var oldName string
	err = db.QueryRow("SELECT name FROM simulations WHERE id = ?", idStr).Scan(&oldName)
	if err != nil {
		http.Error(w, "Simulation not found", http.StatusNotFound)
		return
	}

	// Make sure the new name doesn't already exist
	var tempID int
	err = db.QueryRow("SELECT id FROM simulations WHERE name = ?", newName).Scan(&tempID)
	if err == nil {
		http.Error(w, "A simulation with that name already exists", http.StatusConflict)
		return
	}

	// Rename the physical storage folder to maintain link parity
	oldDirPath := filepath.Join("../results", oldName)
	newDirPath := filepath.Join("../results", newName)
	if _, statErr := os.Stat(oldDirPath); statErr == nil {
		err = os.Rename(oldDirPath, newDirPath)
		if err != nil {
			log.Println("Error renaming directory:", err)
			http.Error(w, "Failed to rename results directory", http.StatusInternalServerError)
			return
		}
	} else {
		// Just ensure target dir exists
		os.MkdirAll(newDirPath, 0755)
	}

	_, err = db.Exec("UPDATE simulations SET name = ? WHERE id = ?", newName, idStr)
	if err != nil {
		// Attempt revert if DB dies halfway 
		os.Rename(newDirPath, oldDirPath)
		log.Println("Update simulation name error:", err)
		http.Error(w, "Failed to update database", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]string{"status": "success", "new_name": newName})
}

func uploadSimulationResource(w http.ResponseWriter, r *http.Request, idStr string) {
	var simName string
	err := db.QueryRow("SELECT name FROM simulations WHERE id = ?", idStr).Scan(&simName)
	if err != nil {
		if err == sql.ErrNoRows {
			http.Error(w, "Simulation not found", http.StatusNotFound)
		} else {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
		return
	}

	err = r.ParseMultipartForm(500 << 20) // 500 MB max memory/file bounds
	if err != nil {
		http.Error(w, "Error parsing form: "+err.Error(), http.StatusBadRequest)
		return
	}

	file, handler, err := r.FormFile("file")
	if err != nil {
		http.Error(w, "Error retrieving the file", http.StatusBadRequest)
		return
	}
	defer file.Close()

	destPath := filepath.Join("../results", simName, handler.Filename)
	dst, err := os.Create(destPath)
	if err != nil {
		http.Error(w, "Error creating destination file: "+err.Error(), http.StatusInternalServerError)
		return
	}
	defer dst.Close()

	_, err = io.Copy(dst, file)
	if err != nil {
		http.Error(w, "Error saving file: "+err.Error(), http.StatusInternalServerError)
		return
	}

	// Route through faststart transcoder if it happens to be an .avi
	finalFilename := transcodeIfNeeded(filepath.Join("../results", simName), handler.Filename)

	var resID int
	err = db.QueryRow("SELECT id FROM resources WHERE simulation_id = ? AND filename = ?", idStr, finalFilename).Scan(&resID)
	if err == sql.ErrNoRows {
		_, err = db.Exec("INSERT INTO resources(simulation_id, filename) VALUES(?, ?)", idStr, finalFilename)
		if err != nil {
			log.Println("Error inserting uploaded resource into db:", err)
		}
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]string{
		"status":   "success",
		"filename": finalFilename,
	})
}
