package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"sort"
	"strings"
	"syscall"

	"github.com/duffy/usb-server/internal/bridge"
	"github.com/duffy/usb-server/internal/client"
	"github.com/duffy/usb-server/internal/config"
	"github.com/duffy/usb-server/internal/diag"
	"github.com/duffy/usb-server/internal/protocol"
	"github.com/duffy/usb-server/internal/service"
	"github.com/duffy/usb-server/internal/token"
	"github.com/duffy/usb-server/internal/usb"
	"github.com/duffy/usb-server/internal/web"
)

// version identifies this build in diagnostic reports. Override at build
// time with -ldflags "-X main.version=...".
var version = "dev"

func main() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)

	if len(os.Args) < 2 {
		printUsage()
		os.Exit(1)
	}

	switch os.Args[1] {
	case "generate-token":
		cmdGenerateToken()
	case "share":
		cmdRun("share")
	case "use":
		cmdRun("use")
	case "both":
		cmdRun("both")
	case "list":
		cmdList()
	case "diag":
		cmdDiag()
	case "gui":
		cmdGUI()
	case "config":
		cmdConfig()
	case "install-service":
		cmdInstallService()
	case "uninstall-service":
		cmdUninstallService()
	case "help", "-h", "--help":
		printUsage()
	default:
		fmt.Fprintf(os.Stderr, "Unknown command: %s\n", os.Args[1])
		printUsage()
		os.Exit(1)
	}
}

func printUsage() {
	fmt.Println(`USB Client - USB over IP

Usage:
  usb-client <command> [options]

Commands:
  generate-token     Generate 3 tokens and compute hash
  share              Start in share mode (expose USB devices)
  use                Start in use mode (consume USB devices)
  both               Start in combined mode (expose and consume)
  list               List local USB devices (-v adds interfaces and endpoints)
  diag               Report why sharing does or does not work on this machine
  gui                Start web UI only
  config             Show current configuration
  install-service    Install as systemd service
  uninstall-service  Remove systemd service
  help               Show this help

Options:
  --config <path>    Config file path (default: ~/.usb-server/config.json)
  --relay <addr>     Relay server address (e.g. ws://localhost:8443)
  --hash <hash>      Group hash
  --name <name>      Client name
  --web-port <port>  Web UI port (default: 8080)
  --no-gui           Disable web UI`)
}

func loadConfig() (*config.Config, string) {
	cfgPath := config.DefaultConfigPath()

	// Check for --config flag in os.Args
	for i, arg := range os.Args {
		if arg == "--config" && i+1 < len(os.Args) {
			cfgPath = os.Args[i+1]
		}
	}

	cfg, err := config.Load(cfgPath)
	if err != nil {
		cfg = config.DefaultConfig()
	}

	// Override with flags
	for i := 2; i < len(os.Args); i++ {
		switch os.Args[i] {
		case "--relay":
			if i+1 < len(os.Args) {
				cfg.RelayAddr = os.Args[i+1]
				i++
			}
		case "--hash":
			if i+1 < len(os.Args) {
				cfg.Hash = os.Args[i+1]
				i++
			}
		case "--name":
			if i+1 < len(os.Args) {
				cfg.Name = os.Args[i+1]
				i++
			}
		case "--web-port":
			if i+1 < len(os.Args) {
				fmt.Sscanf(os.Args[i+1], "%d", &cfg.WebPort)
				i++
			}
		}
	}

	return cfg, cfgPath
}

func cmdGenerateToken() {
	tokens, err := token.Generate()
	if err != nil {
		log.Fatalf("Error generating tokens: %v", err)
	}

	hash := tokens.Hash()

	fmt.Println("Generated Tokens:")
	fmt.Println("=================")
	fmt.Printf("Token 1: %s\n", tokens.Token1)
	fmt.Printf("Token 2: %s\n", tokens.Token2)
	fmt.Printf("Token 3: %s\n", tokens.Token3)
	fmt.Println()
	fmt.Printf("Hash:    %s\n", hash)
	fmt.Println()
	fmt.Println("Copy all 3 tokens to all clients that should share USB devices.")
	fmt.Println("The hash is computed from the tokens and used for grouping.")

	// Optionally save to config
	cfg, cfgPath := loadConfig()
	cfg.Token1 = tokens.Token1
	cfg.Token2 = tokens.Token2
	cfg.Token3 = tokens.Token3
	cfg.Hash = hash
	if err := cfg.Save(cfgPath); err != nil {
		log.Printf("Warning: could not save config: %v", err)
	} else {
		fmt.Printf("\nTokens saved to %s\n", cfgPath)
	}
}

func cmdRun(mode string) {
	cfg, cfgPath := loadConfig()
	cfg.Mode = mode

	if !protocol.ValidMode(cfg.Mode) {
		fmt.Fprintf(os.Stderr, "Error: invalid mode %q (expected share, use or both)\n", cfg.Mode)
		os.Exit(1)
	}

	if cfg.Hash == "" {
		fmt.Println("Error: No hash configured. Run 'usb-client generate-token' first or set --hash.")
		os.Exit(1)
	}

	// Check for --no-gui
	noGUI := false
	for _, arg := range os.Args {
		if arg == "--no-gui" {
			noGUI = true
		}
	}

	c := client.NewClient(cfg)

	// Create the managers this mode needs. In "both" mode they coexist on one
	// relay connection: the share manager answers device requests from peers
	// while the use manager attaches devices those peers offer.
	var sm *client.ShareManager
	var um *client.UseManager

	if protocol.CanShare(cfg.Mode) {
		sm = client.NewShareManager(c, cfg)
	}
	if protocol.CanUse(cfg.Mode) {
		um = client.NewUseManager(c, cfg, cfgPath)
	}

	// Accept devices handed in by a supervising process, where configured.
	// This is how an Android app shares devices it had to obtain through the
	// framework; on an ordinary Linux host it stays off.
	var bridgeServer *bridge.Server
	if cfg.BridgeSocket != "" && sm != nil {
		bs, err := bridge.Listen(cfg.BridgeSocket)
		if err != nil {
			log.Printf("Device bridge unavailable: %v", err)
		} else {
			bs.OnChange = sm.RefreshNow
			bridgeServer = bs
			defer bs.Close()
		}
	}

	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

	// web_port 0 disables the UI as surely as --no-gui does. Binding to port 0
	// would otherwise pick an arbitrary port, which on a shared machine means
	// an unexpected open control interface.
	if !noGUI && cfg.WebPort > 0 {
		webHandler := buildWebHandler(cfg, cfgPath, c, sm, um)
		addr := fmt.Sprintf(":%d", cfg.WebPort)
		log.Printf("Web UI available at http://localhost%s", addr)
		go func() {
			if err := http.ListenAndServe(addr, webHandler); err != nil {
				log.Printf("Web UI error: %v", err)
			}
		}()
	}

	go func() {
		if err := c.Run(); err != nil {
			log.Printf("Client error: %v", err)
		}
	}()

	if sm != nil {
		go sm.Run()
	}

	log.Printf("USB Client started (mode=%s, name=%s)", cfg.Mode, cfg.Name)

	sig := <-sigChan
	log.Printf("Received signal %v, shutting down...", sig)

	// Release devices before dropping the relay link, so peers are told
	// rather than left waiting for a timeout.
	if um != nil {
		um.Cleanup()
	}
	if bridgeServer != nil {
		bridgeServer.Close()
	}
	c.Close()
}

// buildWebHandler wires the HTTP API to whichever managers are active.
func buildWebHandler(cfg *config.Config, cfgPath string, c *client.Client,
	sm *client.ShareManager, um *client.UseManager) *web.Handler {

	h := web.NewHandler(cfg, cfgPath)

	h.GetStatus = func() map[string]interface{} {
		status := map[string]interface{}{
			"connected": c.Connected(),
			"mode":      cfg.Mode,
			"name":      cfg.Name,
			"client_id": c.ID(),
			"can_share": sm != nil,
			"can_use":   um != nil,
			"encrypted": c.TunnelSecret() != nil,
		}
		if sm != nil {
			status["direct_port"] = sm.DirectPort()
		}
		return status
	}

	h.GetDevices = func() interface{} {
		result := map[string]interface{}{"mode": cfg.Mode}

		if sm != nil {
			result["local_devices"] = sm.DeviceListForAPI()
		}

		if um != nil {
			var availList []map[string]interface{}
			for _, d := range um.GetAvailableDevices() {
				availList = append(availList, map[string]interface{}{
					"bus_id":             d.BusID,
					"vendor_id":          d.VendorID,
					"product_id":         d.ProductID,
					"name":               d.Name,
					"status":             d.Status,
					"speed":              d.Speed,
					"client_id":          d.ClientID,
					"client_name":        d.ClientName,
					"allow_force_detach": um.IsForceDetachable(d.ClientID),
					"auto_connect":       um.IsAutoConnect(d.VendorID, d.ProductID),
				})
			}

			var attachList []map[string]interface{}
			for _, d := range um.GetAttachedDevices() {
				attachList = append(attachList, map[string]interface{}{
					"bus_id":       d.BusID,
					"vendor_id":    d.VendorID,
					"product_id":   d.ProductID,
					"name":         d.Name,
					"client_id":    d.ClientID,
					"client_name":  d.ClientName,
					"tunnel_id":    d.TunnelID,
					"vhci_port":    d.VHCIPort,
					"auto_connect": um.IsAutoConnect(d.VendorID, d.ProductID),
				})
			}

			result["available_devices"] = availList
			result["attached_devices"] = attachList
		}

		return result
	}

	if um != nil {
		h.AttachDevice = um.AttachDevice
		h.DetachDevice = um.DetachDevice
		h.ForceDetachDevice = um.ForceDetachDevice
		h.SetAutoConnect = um.SetAutoConnect
		h.IsAutoConnect = um.IsAutoConnect
	}

	h.InstallService = func() error { return service.Install(cfg.Mode, cfgPath) }
	h.UninstallService = service.Uninstall

	return h
}

func cmdList() {
	devices, err := usb.Enumerate()
	if err != nil {
		log.Fatalf("Error enumerating USB devices: %v", err)
	}

	if len(devices) == 0 {
		fmt.Println("No USB devices found.")
		return
	}

	verbose := false
	for _, arg := range os.Args {
		if arg == "-v" || arg == "--verbose" {
			verbose = true
		}
	}
	if verbose {
		listVerbose(devices)
		return
	}

	fmt.Printf("%-10s %-10s %-30s %-8s %s\n", "BUS-ID", "VID:PID", "NAME", "SPEED", "DRIVER")
	fmt.Println(strings.Repeat("-", 80))

	for _, dev := range devices {
		driver := ""
		if len(dev.Interfaces) > 0 {
			driver = dev.Interfaces[0].Driver
		}
		speedNames := map[uint32]string{
			1: "Low", 2: "Full", 3: "High", 5: "Super", 6: "Super+",
		}
		speed := speedNames[dev.Speed]
		if speed == "" {
			speed = "?"
		}

		fmt.Printf("%-10s %04x:%04x  %-30s %-8s %s\n",
			dev.BusID,
			dev.VendorID, dev.ProductID,
			truncate(dev.DisplayName(), 30),
			speed,
			driver,
		)
	}
}

// listVerbose prints interfaces and endpoints per device.
//
// The endpoint transfer types shown here are exactly what the share side uses
// to decide how to submit each URB, so this is the first place to look when a
// device attaches but produces no traffic.
func listVerbose(devices []usb.Device) {
	typeNames := map[uint8]string{
		usb.TransferTypeControl:     "control",
		usb.TransferTypeIsochronous: "isochronous",
		usb.TransferTypeBulk:        "bulk",
		usb.TransferTypeInterrupt:   "interrupt",
	}

	for i, dev := range devices {
		if i > 0 {
			fmt.Println()
		}
		fmt.Printf("%s  %04x:%04x  %s\n", dev.BusID, dev.VendorID, dev.ProductID, dev.DisplayName())
		fmt.Printf("  path=%s speed=%d config=%d\n", dev.DevPath, dev.Speed, dev.ConfigValue)

		for _, iface := range dev.Interfaces {
			driver := iface.Driver
			if driver == "" {
				driver = "(none)"
			}
			fmt.Printf("  interface %d: class=%02x subclass=%02x protocol=%02x driver=%s\n",
				iface.Number, iface.Class, iface.SubClass, iface.Protocol, driver)
		}

		if len(dev.Endpoints) == 0 {
			fmt.Printf("  endpoints: none read — run as root to read %s\n", dev.DevPath)
			continue
		}

		// Sort by address so repeated runs are comparable.
		addrs := make([]int, 0, len(dev.Endpoints))
		for addr := range dev.Endpoints {
			addrs = append(addrs, int(addr))
		}
		sort.Ints(addrs)

		fmt.Println("  endpoints (all alternate settings):")
		for _, a := range addrs {
			ep := dev.Endpoints[uint8(a)]
			dir := "OUT"
			if ep.IsIn() {
				dir = "IN"
			}
			fmt.Printf("    0x%02x  EP%-2d %-3s  %-11s  maxpkt=%-4d interval=%d\n",
				ep.Address, ep.Number(), dir, typeNames[ep.TransferType], ep.MaxPacketSize, ep.Interval)
		}
	}
}

// cmdDiag collects and reports the machine's USB situation.
//
// The point is to replace "it does not work" with facts: which mechanism
// would be used here, what is missing, and what to do about it. Every failure
// mode this code has is platform specific and mostly invisible otherwise.
func cmdDiag() {
	fs := flag.NewFlagSet("diag", flag.ExitOnError)
	asJSON := fs.Bool("json", false, "emit JSON instead of text")
	outFile := fs.String("out", "", "write to this file as well as stdout")
	upload := fs.String("upload", "", "upload to this relay (defaults to the configured one when -id is given)")
	reportID := fs.String("id", "", "report ID to upload under")
	fs.Parse(os.Args[2:])

	report := diag.Collect(version)

	var output []byte
	if *asJSON {
		data, err := report.JSON()
		if err != nil {
			log.Fatalf("Error encoding report: %v", err)
		}
		output = data
	} else {
		output = []byte(report.String())
	}

	fmt.Println(string(output))

	if *outFile != "" {
		if err := os.WriteFile(*outFile, output, 0600); err != nil {
			log.Printf("Warning: could not write %s: %v", *outFile, err)
		} else {
			fmt.Printf("\nWritten to %s\n", *outFile)
		}
	}

	if *reportID != "" {
		relayAddr := *upload
		if relayAddr == "" {
			cfg, _ := loadConfig()
			relayAddr = cfg.RelayAddr
		}
		if relayAddr == "" {
			log.Fatalf("No relay to upload to: pass -upload or configure one first")
		}

		url, err := diag.Upload(relayAddr, *reportID, report)
		if err != nil {
			log.Fatalf("Upload failed: %v", err)
		}
		fmt.Printf("\nUploaded to %s\n", url)
		fmt.Printf("It stays there for %s, or until the relay restarts.\n", diag.RetentionNote)
	}
}

func cmdGUI() {
	cfg, cfgPath := loadConfig()

	webHandler := web.NewHandler(cfg, cfgPath)
	webHandler.GetDevices = func() interface{} {
		devices, _ := usb.Enumerate()
		var devList []map[string]interface{}
		for _, d := range devices {
			devList = append(devList, map[string]interface{}{
				"bus_id":     d.BusID,
				"vendor_id":  fmt.Sprintf("%04x", d.VendorID),
				"product_id": fmt.Sprintf("%04x", d.ProductID),
				"name":       d.DisplayName(),
				"status":     "available",
				"speed":      d.Speed,
			})
		}
		return map[string]interface{}{
			"mode":          cfg.Mode,
			"local_devices": devList,
		}
	}
	webHandler.GetStatus = func() map[string]interface{} {
		return map[string]interface{}{
			"connected": false,
			"mode":      cfg.Mode,
			"name":      cfg.Name,
		}
	}

	addr := fmt.Sprintf(":%d", cfg.WebPort)
	fmt.Printf("Web UI: http://localhost%s\n", addr)
	log.Fatal(http.ListenAndServe(addr, webHandler))
}

func cmdConfig() {
	cfg, cfgPath := loadConfig()

	// Check for subcommand
	if len(os.Args) > 2 && os.Args[2] == "show" || len(os.Args) == 2 {
		fmt.Printf("Config file: %s\n\n", cfgPath)
		data, err := json.MarshalIndent(cfg, "", "  ")
		if err != nil {
			log.Fatalf("Error encoding config: %v", err)
		}
		fmt.Println(string(data))
		return
	}

	// Handle set subcommand
	if os.Args[2] == "set" {
		fs := flag.NewFlagSet("config set", flag.ExitOnError)
		relay := fs.String("relay", "", "Relay server address")
		hash := fs.String("hash", "", "Group hash")
		mode := fs.String("mode", "", "Client mode (share/use)")
		name := fs.String("name", "", "Client name")
		fs.Parse(os.Args[3:])

		if *relay != "" {
			cfg.RelayAddr = *relay
		}
		if *hash != "" {
			cfg.Hash = *hash
		}
		if *mode != "" {
			cfg.Mode = *mode
		}
		if *name != "" {
			cfg.Name = *name
		}

		if err := cfg.Save(cfgPath); err != nil {
			log.Fatalf("Error saving config: %v", err)
		}
		fmt.Println("Config saved.")
		return
	}

	printUsage()
}

func cmdInstallService() {
	cfg, cfgPath := loadConfig()
	if err := service.Install(cfg.Mode, cfgPath); err != nil {
		log.Fatalf("Error installing service: %v", err)
	}
	fmt.Println("Service installed and started.")
}

func cmdUninstallService() {
	if err := service.Uninstall(); err != nil {
		log.Fatalf("Error uninstalling service: %v", err)
	}
	fmt.Println("Service uninstalled.")
}

func truncate(s string, max int) string {
	if len(s) <= max {
		return s
	}
	return s[:max-3] + "..."
}
