// Package wgsync pushes the hub's WG peer registry to the offsite endpoint (S1, doc 06 §5).
// It is the structural sibling of internal/cloudflare: the hub holds the credential and drives
// external infra; the endpoint stays a dumb, runbook-provisioned box. Transport is SSH with a
// PINNED host key (the internal/pbs pin posture — exact-match or refuse; there is no insecure
// fallback), to a forced-command reconcile script server-side, so even this credential's theft
// bounds the attacker to "mutate the peer list" (doc 06 §3.1 blast radius).
package wgsync

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net"
	"strings"
	"time"

	"golang.org/x/crypto/ssh"
)

// Config configures the SSH push client. All values come from the deployment env / mounted
// Secret (operator infra — never from a customer record).
type Config struct {
	Addr        string        // "host:22"
	User        string        // "felhom-peersync"
	PrivateKey  []byte        // PEM private key (from the mounted Secret file)
	HostKeyLine string        // single authorized_keys-format line of the endpoint's host pubkey
	Timeout     time.Duration // default 30s
}

// Client is a pinned-host-key SSH pusher. Construct with New (parses keys up front).
type Client struct {
	addr    string
	user    string
	signer  ssh.Signer
	hostKey ssh.PublicKey
	timeout time.Duration
	logger  *log.Logger
}

// New builds a Client, failing early on an unparsable private key or host-key line.
func New(cfg Config, logger *log.Logger) (*Client, error) {
	if cfg.Addr == "" || cfg.User == "" {
		return nil, fmt.Errorf("wgsync: Addr and User are required")
	}
	signer, err := ssh.ParsePrivateKey(cfg.PrivateKey)
	if err != nil {
		return nil, fmt.Errorf("wgsync: parse private key: %w", err)
	}
	hostKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(cfg.HostKeyLine))
	if err != nil {
		return nil, fmt.Errorf("wgsync: parse host key line: %w", err)
	}
	timeout := cfg.Timeout
	if timeout == 0 {
		timeout = 30 * time.Second
	}
	if logger == nil {
		logger = log.Default()
	}
	return &Client{
		addr: cfg.Addr, user: cfg.User, signer: signer,
		hostKey: hostKey, timeout: timeout, logger: logger,
	}, nil
}

// pushResponse is the peersync script's stdout contract ({"status":"ok","applied":N}).
type pushResponse struct {
	Status  string `json:"status"`
	Applied int    `json:"applied"`
}

// Push sends the payload to the endpoint's forced-command script over one SSH session and
// verifies the script's ok-response. The host key is pinned (ssh.FixedHostKey) — a wrong key is
// a refused connection, never a prompt or a fallback.
func (c *Client) Push(ctx context.Context, payload []byte) error {
	sshCfg := &ssh.ClientConfig{
		User:            c.user,
		Auth:            []ssh.AuthMethod{ssh.PublicKeys(c.signer)},
		HostKeyCallback: ssh.FixedHostKey(c.hostKey),
		// Constrain negotiation to the PINNED key's algorithm. Without this the default
		// algorithm preference makes a multi-hostkey sshd (stock: ECDSA + ed25519) present a
		// different key type than the pinned one — FixedHostKey then refuses a LEGITIMATE
		// server. Found live in the S1 validation (host key mismatch against the real sshd);
		// regression: TestPush_MultiHostkeyServerStillMatchesPin.
		HostKeyAlgorithms: []string{c.hostKey.Type()},
		Timeout:           c.timeout,
	}
	dialer := net.Dialer{Timeout: c.timeout}
	conn, err := dialer.DialContext(ctx, "tcp", c.addr)
	if err != nil {
		return fmt.Errorf("wgsync: dial %s: %w", c.addr, err)
	}
	// Hand the ssh handshake a deadline too — DialContext's ctx stops applying after Dial.
	if dl, ok := ctx.Deadline(); ok {
		conn.SetDeadline(dl)
	} else {
		conn.SetDeadline(time.Now().Add(c.timeout))
	}
	sconn, chans, reqs, err := ssh.NewClientConn(conn, c.addr, sshCfg)
	if err != nil {
		conn.Close()
		return fmt.Errorf("wgsync: ssh handshake %s: %w", c.addr, err)
	}
	client := ssh.NewClient(sconn, chans, reqs)
	defer client.Close()
	conn.SetDeadline(time.Time{}) // handshake done; session I/O below is bounded by the same conn
	if dl, ok := ctx.Deadline(); ok {
		conn.SetDeadline(dl)
	}

	session, err := client.NewSession()
	if err != nil {
		return fmt.Errorf("wgsync: session: %w", err)
	}
	defer session.Close()

	var stdout, stderr bytes.Buffer
	session.Stdin = bytes.NewReader(payload)
	session.Stdout = &stdout
	session.Stderr = &stderr

	// The server's authorized_keys forced command overrides this string, but it MUST be set:
	// some sshd configs log the requested command, and it documents intent on the wire.
	if err := session.Run("felhom-peersync"); err != nil {
		return fmt.Errorf("wgsync: remote peersync failed: %w (stderr: %s)",
			err, strings.TrimSpace(stderr.String()))
	}

	var resp pushResponse
	if err := json.Unmarshal(bytes.TrimSpace(stdout.Bytes()), &resp); err != nil || resp.Status != "ok" {
		return fmt.Errorf("wgsync: malformed peersync response %q (parse err: %v, stderr: %s)",
			strings.TrimSpace(stdout.String()), err, strings.TrimSpace(stderr.String()))
	}
	c.logger.Printf("[INFO] wgsync: pushed %d peers to %s", resp.Applied, c.addr)
	return nil
}
