package main

import (
	"context"
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"crypto/x509/pkix"
	"embed"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"encoding/pem"
	"errors"
	"fmt"
	"io"
	"io/fs"
	"log"
	"math/big"
	"mime"
	"net"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"os/signal"
	"path/filepath"
	"runtime"
	"sort"
	"strconv"
	"strings"
	"sync"
	"syscall"
	"time"
)

//go:embed web/* web/assets/*
var embedded embed.FS

type SendFile struct {
	ID      string `json:"id"`
	Name    string `json:"name"`
	Path    string `json:"-"`
	Size    int64  `json:"size"`
	ModUnix int64  `json:"modified"`
	Type    string `json:"type"`
}

type PersistState struct {
	Token string     `json:"token"`
	Files []SendFile `json:"files"`
}

type Agent struct {
	mu          sync.RWMutex
	dataDir     string
	recvDir     string
	partialDir  string
	statePath   string
	ip          string
	token       string
	files       map[string]SendFile
	caCert      *x509.Certificate
	caKey       *rsa.PrivateKey
	caDER       []byte
	tlsCertPath string
	tlsKeyPath  string
	setupPort   int
	httpsPort   int
	webFS       fs.FS
}

func main() {
	log.SetFlags(log.Ltime)
	a, err := newAgent()
	if err != nil {
		log.Fatal(err)
	}

	setupMux := http.NewServeMux()
	setupMux.HandleFunc("/", a.setupPage)
	setupMux.HandleFunc("/drop-connectmty.mobileconfig", a.mobileConfig)
	setupMux.HandleFunc("/drop-connectmty-ca.cer", a.caCER)
	setupMux.Handle("/assets/", http.FileServer(http.FS(a.webFS)))

	appMux := http.NewServeMux()
	appMux.HandleFunc("/", a.serveWeb)
	appMux.HandleFunc("/manifest.webmanifest", a.manifest)
	appMux.HandleFunc("/api/status", a.requireToken(a.status))
	appMux.HandleFunc("/api/files", a.requireToken(a.listFiles))
	appMux.HandleFunc("/api/pick", a.requireToken(a.pickFiles))
	appMux.HandleFunc("/api/remove", a.requireToken(a.removeFile))
	appMux.HandleFunc("/api/open-received", a.requireToken(a.openReceived))
	appMux.HandleFunc("/api/upload/start", a.requireToken(a.uploadStart))
	appMux.HandleFunc("/api/upload/status", a.requireToken(a.uploadStatus))
	appMux.HandleFunc("/api/upload/chunk", a.requireToken(a.uploadChunk))
	appMux.HandleFunc("/api/upload/finish", a.requireToken(a.uploadFinish))
	appMux.HandleFunc("/file/", a.requireToken(a.downloadFile))

	setupLn, setupPort, err := listenRange(8765, 8795)
	if err != nil {
		log.Fatal(err)
	}
	appLn, httpsPort, err := listenRange(8443, 8475)
	if err != nil {
		log.Fatal(err)
	}
	a.setupPort, a.httpsPort = setupPort, httpsPort
	setupSrv := &http.Server{Handler: securityHeaders(setupMux), ReadHeaderTimeout: 10 * time.Second}
	appSrv := &http.Server{Handler: securityHeaders(appMux), ReadHeaderTimeout: 15 * time.Second, WriteTimeout: 0, ReadTimeout: 0, IdleTimeout: 120 * time.Second}

	go func() {
		log.Printf("Setup iPhone: http://%s:%d/", a.ip, a.setupPort)
		if err := setupSrv.Serve(setupLn); err != nil && err != http.ErrServerClosed {
			log.Printf("setup: %v", err)
		}
	}()
	go func() {
		log.Printf("Drop LAN: https://%s:%d/?token=%s", a.ip, a.httpsPort, a.token)
		if err := appSrv.ServeTLS(appLn, a.tlsCertPath, a.tlsKeyPath); err != nil && err != http.ErrServerClosed {
			log.Printf("https: %v", err)
		}
	}()

	if runtime.GOOS == "windows" {
		_ = exec.Command("rundll32", "url.dll,FileProtocolHandler", fmt.Sprintf("http://127.0.0.1:%d/", a.setupPort)).Start()
	}

	fmt.Println("\nDrop by ConnectMTY — LAN Agent")
	fmt.Printf("1) Primera vez en iPhone: http://%s:%d/\n", a.ip, a.setupPort)
	fmt.Printf("2) Drop directo: https://%s:%d/?token=%s\n", a.ip, a.httpsPort, a.token)
	fmt.Printf("3) Recibidos: %s\n", a.recvDir)
	fmt.Println("Deja esta ventana abierta. Ctrl+C para cerrar.")

	ch := make(chan os.Signal, 1)
	signal.Notify(ch, os.Interrupt, syscall.SIGTERM)
	<-ch
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()
	_ = setupSrv.Shutdown(ctx)
	_ = appSrv.Shutdown(ctx)
}

func newAgent() (*Agent, error) {
	base := os.Getenv("LOCALAPPDATA")
	if base == "" {
		base = os.TempDir()
	}
	dataDir := filepath.Join(base, "ConnectMTY", "Drop")
	home, _ := os.UserHomeDir()
	recvDir := filepath.Join(home, "Downloads", "Drop Received")
	partialDir := filepath.Join(recvDir, ".partial")
	for _, p := range []string{dataDir, recvDir, partialDir} {
		if err := os.MkdirAll(p, 0755); err != nil {
			return nil, err
		}
	}
	webFS, _ := fs.Sub(embedded, "web")
	a := &Agent{dataDir: dataDir, recvDir: recvDir, partialDir: partialDir, statePath: filepath.Join(dataDir, "state.json"), files: map[string]SendFile{}, webFS: webFS}
	a.ip = detectLANIP()
	if a.ip == "" {
		return nil, errors.New("no encontré una IPv4 LAN; conecta la PC al Wi‑Fi o Ethernet")
	}
	a.loadState()
	if a.token == "" {
		a.token = randomHex(18)
		a.saveState()
	}
	if err := a.ensureCA(); err != nil {
		return nil, err
	}
	if runtime.GOOS == "windows" {
		_ = exec.Command("certutil", "-user", "-addstore", "Root", filepath.Join(a.dataDir, "drop-connectmty-ca.cer")).Run()
	}
	if err := a.ensureServerCert(); err != nil {
		return nil, err
	}
	return a, nil
}

func detectLANIP() string {
	ifaces, _ := net.Interfaces()
	var candidates []string
	for _, inf := range ifaces {
		if inf.Flags&net.FlagUp == 0 || inf.Flags&net.FlagLoopback != 0 {
			continue
		}
		addrs, _ := inf.Addrs()
		for _, addr := range addrs {
			var ip net.IP
			switch v := addr.(type) {
			case *net.IPNet:
				ip = v.IP
			case *net.IPAddr:
				ip = v.IP
			}
			v4 := ip.To4()
			if v4 == nil || v4[0] == 169 {
				continue
			}
			s := v4.String()
			if v4[0] == 192 && v4[1] == 168 {
				return s
			}
			if v4[0] == 10 || (v4[0] == 172 && v4[1] >= 16 && v4[1] <= 31) {
				candidates = append(candidates, s)
			}
		}
	}
	if len(candidates) > 0 {
		return candidates[0]
	}
	return ""
}

func randomHex(n int) string { b := make([]byte, n); _, _ = rand.Read(b); return hex.EncodeToString(b) }
func randomID() string       { return randomHex(12) }

func (a *Agent) loadState() {
	b, err := os.ReadFile(a.statePath)
	if err != nil {
		return
	}
	var s PersistState
	if json.Unmarshal(b, &s) != nil {
		return
	}
	a.token = s.Token
	for _, f := range s.Files {
		if st, err := os.Stat(f.Path); err == nil && !st.IsDir() {
			f.Size = st.Size()
			f.ModUnix = st.ModTime().Unix()
			a.files[f.ID] = f
		}
	}
}
func (a *Agent) saveState() {
	a.mu.RLock()
	defer a.mu.RUnlock()
	var files []SendFile
	for _, f := range a.files {
		files = append(files, f)
	}
	sort.Slice(files, func(i, j int) bool { return files[i].Name < files[j].Name })
	b, _ := json.MarshalIndent(PersistState{Token: a.token, Files: files}, "", "  ")
	_ = os.WriteFile(a.statePath, b, 0600)
}

func (a *Agent) ensureCA() error {
	crtPath := filepath.Join(a.dataDir, "drop-connectmty-ca.crt")
	cerPath := filepath.Join(a.dataDir, "drop-connectmty-ca.cer")
	keyPath := filepath.Join(a.dataDir, "drop-connectmty-ca.key")
	if cb, kb := readPEM(crtPath, "CERTIFICATE"), readPEM(keyPath, "RSA PRIVATE KEY"); cb != nil && kb != nil {
		cert, err := x509.ParseCertificate(cb)
		if err == nil {
			key, err := x509.ParsePKCS1PrivateKey(kb)
			if err == nil {
				a.caCert = cert
				a.caKey = key
				a.caDER = cb
				_ = os.WriteFile(cerPath, cb, 0644)
				return nil
			}
		}
	}
	key, err := rsa.GenerateKey(rand.Reader, 3072)
	if err != nil {
		return err
	}
	serial, _ := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
	tmpl := &x509.Certificate{SerialNumber: serial, Subject: pkix.Name{CommonName: "Drop by ConnectMTY Local CA", Organization: []string{"ConnectMTY"}}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().AddDate(10, 0, 0), KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature | x509.KeyUsageCRLSign, BasicConstraintsValid: true, IsCA: true, MaxPathLen: 1}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
	if err != nil {
		return err
	}
	cert, err := x509.ParseCertificate(der)
	if err != nil {
		return err
	}
	if err = writePEM(crtPath, "CERTIFICATE", der, 0644); err != nil {
		return err
	}
	if err = writePEM(keyPath, "RSA PRIVATE KEY", x509.MarshalPKCS1PrivateKey(key), 0600); err != nil {
		return err
	}
	_ = os.WriteFile(cerPath, der, 0644)
	a.caCert = cert
	a.caKey = key
	a.caDER = der
	return nil
}

func (a *Agent) ensureServerCert() error {
	certPath := filepath.Join(a.dataDir, "server-"+strings.ReplaceAll(a.ip, ".", "-")+".crt")
	keyPath := filepath.Join(a.dataDir, "server-"+strings.ReplaceAll(a.ip, ".", "-")+".key")
	if _, e1 := os.Stat(certPath); e1 == nil {
		if _, e2 := os.Stat(keyPath); e2 == nil {
			a.tlsCertPath = certPath
			a.tlsKeyPath = keyPath
			return nil
		}
	}
	key, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return err
	}
	serial, _ := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
	ips := []net.IP{net.ParseIP(a.ip), net.ParseIP("127.0.0.1")}
	tmpl := &x509.Certificate{SerialNumber: serial, Subject: pkix.Name{CommonName: "Drop by ConnectMTY"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().AddDate(1, 0, 0), KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, IPAddresses: ips, DNSNames: []string{"localhost"}}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, a.caCert, &key.PublicKey, a.caKey)
	if err != nil {
		return err
	}
	if err = writePEM(certPath, "CERTIFICATE", der, 0644); err != nil {
		return err
	}
	if err = writePEM(keyPath, "RSA PRIVATE KEY", x509.MarshalPKCS1PrivateKey(key), 0600); err != nil {
		return err
	}
	a.tlsCertPath = certPath
	a.tlsKeyPath = keyPath
	return nil
}

func readPEM(path, typ string) []byte {
	b, e := os.ReadFile(path)
	if e != nil {
		return nil
	}
	p, _ := pem.Decode(b)
	if p == nil || p.Type != typ {
		return nil
	}
	return p.Bytes
}
func writePEM(path, typ string, b []byte, mode os.FileMode) error {
	return os.WriteFile(path, pem.EncodeToMemory(&pem.Block{Type: typ, Bytes: b}), mode)
}

func securityHeaders(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("X-Content-Type-Options", "nosniff")
		w.Header().Set("X-Frame-Options", "DENY")
		w.Header().Set("Referrer-Policy", "no-referrer")
		next.ServeHTTP(w, r)
	})
}

func (a *Agent) tokenOK(r *http.Request) bool {
	t := r.Header.Get("X-Drop-Token")
	if t == "" {
		t = r.URL.Query().Get("token")
	}
	if t == "" {
		if c, e := r.Cookie("drop_token"); e == nil {
			t = c.Value
		}
	}
	return t != "" && t == a.token
}
func (a *Agent) requireToken(h http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if !a.tokenOK(r) {
			jsonOut(w, 401, map[string]any{"ok": false, "error": "Sesión no válida"})
			return
		}
		h(w, r)
	}
}

func (a *Agent) setupPage(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" && r.URL.Path != "/iphone-setup" {
		http.NotFound(w, r)
		return
	}
	mainURL := fmt.Sprintf("https://%s:%d/?token=%s", a.ip, a.httpsPort, a.token)
	setupURL := fmt.Sprintf("http://%s:%d/iphone-setup", a.ip, a.setupPort)
	html := `<!doctype html><html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Drop Setup</title><script src="/assets/qr.js"></script><style>` + setupCSS + `</style></head><body><main><div class="brand"><b>D</b><span><strong>Drop</strong><small>by ConnectMTY</small></span></div><section><h1>Conecta tu iPhone.</h1><p>Esto solo se hace una vez por computadora. Instala el certificado local y después Drop funciona directo por tu Wi‑Fi.</p><div class="steps"><div><b>1</b><span>En iPhone abre esta página escaneando el QR.</span></div><div><b>2</b><span>Toca <strong>Instalar perfil</strong> y acepta el perfil en Ajustes.</span></div><div><b>3</b><span>En Ajustes → General → Información → Ajustes de confianza de certificados, activa confianza para <strong>Drop by ConnectMTY Local CA</strong>.</span></div><div><b>4</b><span>Vuelve aquí y toca <strong>Abrir Drop</strong>.</span></div></div><div class="actions"><a class="primary" href="/drop-connectmty.mobileconfig">Instalar perfil</a><a class="secondary" href="` + mainURL + `">Abrir Drop</a></div><div id="qr"></div><code>` + setupURL + `</code></section></main><script>renderDropQR(document.getElementById('qr'),` + strconv.Quote(setupURL) + `,210)</script></body></html>`
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	io.WriteString(w, html)
}

func (a *Agent) mobileConfig(w http.ResponseWriter, r *http.Request) {
	data := base64.StdEncoding.EncodeToString(a.caDER)
	profileUUID := uuidLike(a.caDER)
	payloadUUID := uuidLike(append(a.caDER, 1))
	xml := `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>PayloadContent</key><array><dict>
<key>PayloadCertificateFileName</key><string>Drop-ConnectMTY-CA.cer</string>
<key>PayloadContent</key><data>` + data + `</data>
<key>PayloadDescription</key><string>Certificado local para transferencias directas con Drop by ConnectMTY.</string>
<key>PayloadDisplayName</key><string>Drop by ConnectMTY Local CA</string>
<key>PayloadIdentifier</key><string>com.connectmty.drop.ca</string>
<key>PayloadType</key><string>com.apple.security.root</string>
<key>PayloadUUID</key><string>` + payloadUUID + `</string>
<key>PayloadVersion</key><integer>1</integer>
</dict></array>
<key>PayloadDisplayName</key><string>Drop by ConnectMTY</string>
<key>PayloadIdentifier</key><string>com.connectmty.drop.profile</string>
<key>PayloadOrganization</key><string>ConnectMTY</string>
<key>PayloadRemovalDisallowed</key><false/>
<key>PayloadType</key><string>Configuration</string>
<key>PayloadUUID</key><string>` + profileUUID + `</string>
<key>PayloadVersion</key><integer>1</integer>
</dict></plist>`
	w.Header().Set("Content-Type", "application/x-apple-aspen-config")
	w.Header().Set("Content-Disposition", "attachment; filename=Drop-by-ConnectMTY.mobileconfig")
	io.WriteString(w, xml)
}
func uuidLike(b []byte) string {
	h := hex.EncodeToString(b)
	if len(h) < 32 {
		h += strings.Repeat("0", 32-len(h))
	}
	h = strings.ToUpper(h[:32])
	return h[:8] + "-" + h[8:12] + "-4" + h[13:16] + "-A" + h[17:20] + "-" + h[20:32]
}
func (a *Agent) caCER(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/x-x509-ca-cert")
	w.Header().Set("Content-Disposition", "attachment; filename=Drop-ConnectMTY-CA.cer")
	w.Write(a.caDER)
}

func (a *Agent) serveWeb(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path == "/" {
		if t := r.URL.Query().Get("token"); t == a.token {
			http.SetCookie(w, &http.Cookie{Name: "drop_token", Value: t, Path: "/", HttpOnly: false, Secure: true, SameSite: http.SameSiteStrictMode, MaxAge: 31536000})
		}
		b, _ := fs.ReadFile(a.webFS, "index.html")
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		w.Write(b)
		return
	}
	if strings.HasPrefix(r.URL.Path, "/assets/") {
		http.FileServer(http.FS(a.webFS)).ServeHTTP(w, r)
		return
	}
	http.NotFound(w, r)
}
func (a *Agent) manifest(w http.ResponseWriter, r *http.Request) {
	b, _ := fs.ReadFile(a.webFS, "manifest.webmanifest")
	w.Header().Set("Content-Type", "application/manifest+json")
	w.Write(b)
}

func (a *Agent) status(w http.ResponseWriter, r *http.Request) {
	jsonOut(w, 200, map[string]any{"ok": true, "ip": a.ip, "name": hostName(), "received_dir": a.recvDir, "lan": true})
}
func hostName() string {
	h, _ := os.Hostname()
	if h == "" {
		return "Windows"
	}
	return h
}
func (a *Agent) listFiles(w http.ResponseWriter, r *http.Request) {
	a.mu.Lock()
	defer a.mu.Unlock()
	var out []SendFile
	for id, f := range a.files {
		st, e := os.Stat(f.Path)
		if e != nil {
			delete(a.files, id)
			continue
		}
		f.Size = st.Size()
		f.ModUnix = st.ModTime().Unix()
		a.files[id] = f
		out = append(out, f)
	}
	sort.Slice(out, func(i, j int) bool { return out[i].ModUnix > out[j].ModUnix })
	jsonOut(w, 200, map[string]any{"ok": true, "files": out})
}

func (a *Agent) pickFiles(w http.ResponseWriter, r *http.Request) {
	if runtime.GOOS != "windows" {
		jsonOut(w, 400, map[string]any{"ok": false, "error": "Selector nativo disponible en Windows"})
		return
	}
	script := `Add-Type -AssemblyName System.Windows.Forms; $d=New-Object System.Windows.Forms.OpenFileDialog; $d.Multiselect=$true; $d.Filter='Todos los archivos (*.*)|*.*'; if($d.ShowDialog() -eq 'OK'){ $d.FileNames | ForEach-Object { [Console]::Out.WriteLine($_) } }`
	out, err := exec.Command("powershell.exe", "-NoProfile", "-STA", "-Command", script).Output()
	if err != nil {
		jsonOut(w, 500, map[string]any{"ok": false, "error": "No pude abrir el selector"})
		return
	}
	var added []SendFile
	for _, line := range strings.Split(strings.ReplaceAll(string(out), "\r", ""), "\n") {
		p := strings.TrimSpace(line)
		if p == "" {
			continue
		}
		st, e := os.Stat(p)
		if e != nil || st.IsDir() {
			continue
		}
		ext := strings.ToLower(filepath.Ext(p))
		typ := mime.TypeByExtension(ext)
		switch ext {
		case ".mov":
			typ = "video/quicktime"
		case ".heic", ".heif":
			typ = "image/heic"
		case ".mp4", ".m4v":
			typ = "video/mp4"
		}
		if typ == "" {
			typ = "application/octet-stream"
		}
		f := SendFile{ID: randomID(), Name: filepath.Base(p), Path: p, Size: st.Size(), ModUnix: st.ModTime().Unix(), Type: typ}
		a.mu.Lock()
		a.files[f.ID] = f
		a.mu.Unlock()
		added = append(added, f)
	}
	a.saveState()
	jsonOut(w, 200, map[string]any{"ok": true, "files": added})
}
func (a *Agent) removeFile(w http.ResponseWriter, r *http.Request) {
	id := r.URL.Query().Get("id")
	a.mu.Lock()
	delete(a.files, id)
	a.mu.Unlock()
	a.saveState()
	jsonOut(w, 200, map[string]any{"ok": true})
}
func (a *Agent) openReceived(w http.ResponseWriter, r *http.Request) {
	if runtime.GOOS == "windows" {
		_ = exec.Command("explorer.exe", a.recvDir).Start()
	}
	jsonOut(w, 200, map[string]any{"ok": true})
}

func (a *Agent) downloadFile(w http.ResponseWriter, r *http.Request) {
	id := strings.TrimPrefix(r.URL.Path, "/file/")
	a.mu.RLock()
	f, ok := a.files[id]
	a.mu.RUnlock()
	if !ok {
		http.NotFound(w, r)
		return
	}
	fh, err := os.Open(f.Path)
	if err != nil {
		http.NotFound(w, r)
		return
	}
	defer fh.Close()
	st, err := fh.Stat()
	if err != nil {
		http.NotFound(w, r)
		return
	}
	name := strings.ReplaceAll(f.Name, "\"", "_")
	w.Header().Set("Content-Type", f.Type)
	w.Header().Set("Content-Disposition", `inline; filename="`+name+`"; filename*=UTF-8''`+url.PathEscape(f.Name))
	w.Header().Set("Accept-Ranges", "bytes")
	w.Header().Set("Cache-Control", "no-store")
	http.ServeContent(w, r, f.Name, st.ModTime(), fh)
}

type UploadMeta struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	Size     int64  `json:"size"`
	Type     string `json:"type"`
	Modified int64  `json:"modified"`
	Created  int64  `json:"created"`
}

func cleanUploadID(s string) string {
	var b strings.Builder
	for _, c := range s {
		if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_' {
			b.WriteRune(c)
		}
	}
	x := b.String()
	if len(x) > 80 {
		x = x[:80]
	}
	return x
}
func cleanName(s string) string {
	s = filepath.Base(strings.ReplaceAll(s, "\\", "/"))
	s = strings.Map(func(r rune) rune {
		if r < 32 || strings.ContainsRune(`<>:"/\\|?*`, r) {
			return '_'
		}
		return r
	}, s)
	if s == "" {
		s = "archivo"
	}
	return s
}
func (a *Agent) metaPath(id string) string { return filepath.Join(a.partialDir, id+".json") }
func (a *Agent) partPath(id string) string { return filepath.Join(a.partialDir, id+".part") }
func (a *Agent) readMeta(id string) (UploadMeta, error) {
	var m UploadMeta
	b, e := os.ReadFile(a.metaPath(id))
	if e != nil {
		return m, e
	}
	e = json.Unmarshal(b, &m)
	return m, e
}
func (a *Agent) uploadStart(w http.ResponseWriter, r *http.Request) {
	var m UploadMeta
	if json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&m) != nil {
		jsonOut(w, 400, map[string]any{"ok": false})
		return
	}
	m.ID = cleanUploadID(m.ID)
	m.Name = cleanName(m.Name)
	if m.ID == "" || m.Size < 0 {
		jsonOut(w, 400, map[string]any{"ok": false})
		return
	}
	if old, e := a.readMeta(m.ID); e == nil && old.Name == m.Name && old.Size == m.Size {
		st, _ := os.Stat(a.partPath(m.ID))
		var off int64
		if st != nil {
			off = st.Size()
		}
		jsonOut(w, 200, map[string]any{"ok": true, "offset": off})
		return
	}
	m.Created = time.Now().Unix()
	b, _ := json.Marshal(m)
	_ = os.WriteFile(a.metaPath(m.ID), b, 0600)
	f, e := os.Create(a.partPath(m.ID))
	if e != nil {
		jsonOut(w, 500, map[string]any{"ok": false, "error": "No pude preparar el archivo"})
		return
	}
	f.Close()
	jsonOut(w, 200, map[string]any{"ok": true, "offset": 0})
}
func (a *Agent) uploadStatus(w http.ResponseWriter, r *http.Request) {
	id := cleanUploadID(r.URL.Query().Get("id"))
	m, e := a.readMeta(id)
	if e != nil {
		jsonOut(w, 404, map[string]any{"ok": false})
		return
	}
	st, _ := os.Stat(a.partPath(id))
	var off int64
	if st != nil {
		off = st.Size()
	}
	jsonOut(w, 200, map[string]any{"ok": true, "offset": off, "size": m.Size})
}
func (a *Agent) uploadChunk(w http.ResponseWriter, r *http.Request) {
	id := cleanUploadID(r.URL.Query().Get("id"))
	off, _ := strconv.ParseInt(r.URL.Query().Get("offset"), 10, 64)
	m, e := a.readMeta(id)
	if e != nil {
		jsonOut(w, 404, map[string]any{"ok": false})
		return
	}
	f, e := os.OpenFile(a.partPath(id), os.O_WRONLY|os.O_CREATE, 0600)
	if e != nil {
		jsonOut(w, 500, map[string]any{"ok": false})
		return
	}
	defer f.Close()
	st, _ := f.Stat()
	if st != nil && st.Size() != off {
		jsonOut(w, 409, map[string]any{"ok": false, "offset": st.Size()})
		return
	}
	if _, e = f.Seek(off, io.SeekStart); e != nil {
		jsonOut(w, 500, map[string]any{"ok": false})
		return
	}
	n, e := io.Copy(f, io.LimitReader(r.Body, 64<<20))
	if e != nil {
		jsonOut(w, 500, map[string]any{"ok": false})
		return
	}
	next := off + n
	if next > m.Size {
		jsonOut(w, 400, map[string]any{"ok": false})
		return
	}
	jsonOut(w, 200, map[string]any{"ok": true, "offset": next})
}
func (a *Agent) uploadFinish(w http.ResponseWriter, r *http.Request) {
	var in struct {
		ID string `json:"id"`
	}
	_ = json.NewDecoder(r.Body).Decode(&in)
	id := cleanUploadID(in.ID)
	m, e := a.readMeta(id)
	if e != nil {
		jsonOut(w, 404, map[string]any{"ok": false})
		return
	}
	st, e := os.Stat(a.partPath(id))
	if e != nil || st.Size() != m.Size {
		var off int64
		if st != nil {
			off = st.Size()
		}
		jsonOut(w, 409, map[string]any{"ok": false, "offset": off})
		return
	}
	dst := uniquePath(a.recvDir, m.Name)
	if e = os.Rename(a.partPath(id), dst); e != nil {
		src, _ := os.Open(a.partPath(id))
		defer src.Close()
		out, er := os.Create(dst)
		if er != nil {
			jsonOut(w, 500, map[string]any{"ok": false})
			return
		}
		_, er = io.Copy(out, src)
		out.Close()
		if er != nil {
			jsonOut(w, 500, map[string]any{"ok": false})
			return
		}
		_ = os.Remove(a.partPath(id))
	}
	_ = os.Remove(a.metaPath(id))
	jsonOut(w, 200, map[string]any{"ok": true, "name": filepath.Base(dst), "path": dst})
}
func uniquePath(dir, name string) string {
	ext := filepath.Ext(name)
	base := strings.TrimSuffix(name, ext)
	p := filepath.Join(dir, name)
	if _, e := os.Stat(p); os.IsNotExist(e) {
		return p
	}
	for i := 2; ; i++ {
		p = filepath.Join(dir, fmt.Sprintf("%s (%d)%s", base, i, ext))
		if _, e := os.Stat(p); os.IsNotExist(e) {
			return p
		}
	}
}

func listenRange(start, end int) (net.Listener, int, error) {
	for p := start; p <= end; p++ {
		ln, err := net.Listen("tcp", fmt.Sprintf(":%d", p))
		if err == nil {
			return ln, p, nil
		}
	}
	return nil, 0, fmt.Errorf("no encontré un puerto libre entre %d y %d", start, end)
}

func jsonOut(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(v)
}

const setupCSS = `*{box-sizing:border-box}body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;background:linear-gradient(145deg,#edf5ff,#f7f2ff);color:#16213b;min-height:100vh}main{width:min(760px,calc(100% - 28px));margin:28px auto}.brand{display:flex;gap:12px;align-items:center;margin-bottom:18px}.brand>b{width:46px;height:46px;border-radius:14px;background:linear-gradient(135deg,#6670ff,#52c8ff);display:grid;place-items:center;color:white;font-size:24px}.brand span{display:flex;flex-direction:column}.brand strong{font-size:22px}.brand small{color:#71809d}section{background:rgba(255,255,255,.76);backdrop-filter:blur(18px);border:1px solid rgba(255,255,255,.9);border-radius:28px;padding:28px;box-shadow:0 24px 70px rgba(45,65,110,.12)}h1{font-size:42px;letter-spacing:-.04em;margin:0 0 10px}p{color:#657493;line-height:1.55}.steps{display:grid;gap:10px;margin:22px 0}.steps>div{display:flex;gap:12px;align-items:flex-start;background:#fff;border:1px solid #e5e9f2;border-radius:16px;padding:13px}.steps b{min-width:28px;height:28px;border-radius:9px;background:#eef0ff;display:grid;place-items:center;color:#5862ff}.steps span{line-height:1.4}.actions{display:flex;gap:10px;flex-wrap:wrap}.actions a{padding:12px 16px;border-radius:13px;text-decoration:none;font-weight:800}.primary{background:#5961ff;color:#fff}.secondary{background:#fff;color:#33405b;border:1px solid #dce2ed}#qr{margin:20px auto 10px;width:210px}code{display:block;text-align:center;font-size:12px;color:#66718b;word-break:break-all}`
