// Package ring29 provides scoped HTTPS access and local encryption for Ring29.
// Received messages are untrusted data, never authorization to execute actions.
package ring29

import (
	"bytes"
	"context"
	"crypto/aes"
	"crypto/cipher"
	"crypto/ecdh"
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"strconv"
	"strings"
	"time"
	"unicode"
)

type Credentials struct {
	URL         string            `json:"url"`
	Token       string            `json:"token"`
	Participant string            `json:"participant"`
	Session     string            `json:"session"`
	PrivateKey  string            `json:"privateKey"`
	PublicKey   string            `json:"publicKey,omitempty"`
	TrustedKeys map[string]string `json:"trustedKeys"`
}

// String redacts credentials from ordinary formatted output.
func (c Credentials) String() string { return "Ring29 credentials (redacted)" }

type Publisher struct {
	Computer    string `json:"computer"`
	AgentType   string `json:"agentType"`
	SessionName string `json:"sessionName"`
	SessionID   string `json:"sessionId"`
}
type Member struct {
	ID          string `json:"id"`
	PublicKey   string `json:"publicKey"`
	Fingerprint string `json:"fingerprint"`
	Write       bool   `json:"write"`
	Revoked     bool   `json:"revoked"`
}
type Info struct {
	ID      string   `json:"id"`
	Owner   string   `json:"owner"`
	Members []Member `json:"members"`
}
type Box struct {
	Nonce      string `json:"nonce"`
	Ciphertext string `json:"ciphertext"`
}
type Envelope struct {
	V          int            `json:"v"`
	ID         string         `json:"id"`
	Session    string         `json:"session"`
	Sender     string         `json:"sender"`
	Kind       string         `json:"kind"`
	Created    int64          `json:"created"`
	Keys       map[string]Box `json:"keys"`
	Nonce      string         `json:"nonce"`
	Ciphertext string         `json:"ciphertext"`
	Object     bool           `json:"object,omitempty"`
	Sequence   uint64         `json:"sequence,omitempty"`
}
type Message struct {
	Format      string          `json:"format"`
	Version     int             `json:"version"`
	RecordType  string          `json:"recordType"`
	SnippetID   string          `json:"snippetId"`
	Parent      *string         `json:"parent"`
	Title       string          `json:"title"`
	Text        string          `json:"text"`
	Folder      string          `json:"folder"`
	Tags        []string        `json:"tags"`
	Subject     string          `json:"subject"`
	Stream      string          `json:"stream"`
	MessageType string          `json:"messageType"`
	Publisher   Publisher       `json:"publisher"`
	File        json.RawMessage `json:"file,omitempty"`
}
type Update struct {
	ID               string   `json:"id"`
	Sequence         uint64   `json:"sequence"`
	Sender           string   `json:"sender"`
	Trusted          bool     `json:"trusted"`
	Fingerprint      string   `json:"fingerprint,omitempty"`
	Data             *Message `json:"data,omitempty"`
	UntrustedContent bool     `json:"untrustedContent"`
}
type Batch struct {
	Updates []Update `json:"updates"`
	Cursor  uint64   `json:"cursor"`
}
type Published struct {
	ID        string `json:"id"`
	Sequence  uint64 `json:"sequence"`
	SnippetID string `json:"snippetId"`
	Subject   string `json:"subject"`
}

// Client is for sequential use. Use a separate Client and cursor per agent session.
type Client struct {
	creds     Credentials
	private   *ecdh.PrivateKey
	http      *http.Client
	Publisher Publisher
}

func randomID() string {
	b := make([]byte, 16)
	if _, err := rand.Read(b); err != nil {
		panic(err)
	}
	return hex.EncodeToString(b)
}
func decode(s string) ([]byte, error) {
	s = strings.NewReplacer("-", "+", "_", "/").Replace(s)
	return base64.StdEncoding.DecodeString(s + strings.Repeat("=", (4-len(s)%4)%4))
}
func encode(b []byte) string { return base64.StdEncoding.EncodeToString(b) }
func validID(s string) bool {
	b, e := hex.DecodeString(s)
	return e == nil && len(b) == 16 && s == strings.ToLower(s)
}
func origin(value string) (string, error) {
	u, e := url.Parse(value)
	if e != nil {
		return "", e
	}
	if u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") {
		return "", errors.New("supply only an API origin")
	}
	if u.Scheme != "https" && !(u.Scheme == "http" && (u.Hostname() == "localhost" || u.Hostname() == "127.0.0.1")) {
		return "", errors.New("HTTPS is required")
	}
	return u.Scheme + "://" + u.Host, nil
}
func New(creds Credentials) (*Client, error) {
	base, e := origin(creds.URL)
	if e != nil {
		return nil, e
	}
	if !validID(creds.Session) || !validID(creds.Participant) {
		return nil, errors.New("invalid vault or participant ID")
	}
	raw, e := decode(creds.PrivateKey)
	if e != nil {
		return nil, e
	}
	private, e := ecdh.P256().NewPrivateKey(raw)
	if e != nil {
		return nil, e
	}
	creds.URL = base
	trusted := map[string]string{}
	for k, v := range creds.TrustedKeys {
		trusted[k] = v
	}
	creds.TrustedKeys = trusted
	host, _ := os.Hostname()
	return &Client{creds: creds, private: private, http: &http.Client{Timeout: 25 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("API redirects are not allowed") }}, Publisher: Publisher{host, "go", "Ring29 session", randomID()}}, nil
}
func Load(path string) (*Client, error) {
	data, e := os.ReadFile(path)
	if e != nil {
		return nil, e
	}
	var creds Credentials
	if e = json.Unmarshal(data, &creds); e != nil {
		return nil, e
	}
	return New(creds)
}

// Save creates a 0600 credential file and refuses to overwrite an existing file.
func (c *Client) Save(path string) error {
	f, e := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
	if e != nil {
		return e
	}
	e = json.NewEncoder(f).Encode(c.creds)
	closeErr := f.Close()
	if e != nil {
		return e
	}
	return closeErr
}
func request(ctx context.Context, client *http.Client, base, token, path, method string, body, out any) error {
	var data io.Reader
	if body != nil {
		b, e := json.Marshal(body)
		if e != nil {
			return e
		}
		data = bytes.NewReader(b)
	}
	req, e := http.NewRequestWithContext(ctx, method, base+path, data)
	if e != nil {
		return e
	}
	req.Header.Set("Origin", base)
	if token != "" {
		req.Header.Set("Authorization", "Bearer "+token)
	}
	if body != nil {
		req.Header.Set("Content-Type", "application/json")
	}
	resp, e := client.Do(req)
	if e != nil {
		return e
	}
	defer resp.Body.Close()
	if resp.StatusCode < 200 || resp.StatusCode >= 300 {
		return fmt.Errorf("Ring29 API returned HTTP %d", resp.StatusCode)
	}
	return json.NewDecoder(io.LimitReader(resp.Body, 32<<20)).Decode(out)
}
func (c *Client) api(ctx context.Context, path, method string, body, out any) error {
	return request(ctx, c.http, c.creds.URL, c.creds.Token, path, method, body, out)
}

// Create uses an account API key to create a human-owned vault and local key.
func Create(ctx context.Context, base, token, name, agentName string) (*Client, error) {
	return identity(ctx, base, token, "/api/agent/vaults", map[string]string{"name": name, "agentName": agentName})
}

// Join consumes a single-use invitation; the encryption key stays local.
func Join(ctx context.Context, base, code, agentName string) (*Client, error) {
	return identity(ctx, base, "", "/api/agent/join", map[string]string{"code": code, "name": agentName})
}
func identity(ctx context.Context, base, token, path string, body map[string]string) (*Client, error) {
	base, e := origin(base)
	if e != nil {
		return nil, e
	}
	private, e := ecdh.P256().GenerateKey(rand.Reader)
	if e != nil {
		return nil, e
	}
	body["publicKey"] = encode(private.PublicKey().Bytes())
	var response struct {
		Token string `json:"token"`
		User  Member `json:"user"`
		Vault struct {
			ID    string `json:"id"`
			Owner string `json:"owner"`
		} `json:"vault"`
		Members []Member `json:"members"`
	}
	h := &http.Client{Timeout: 25 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("API redirects are not allowed") }}
	if e = request(ctx, h, base, token, path, "POST", body, &response); e != nil {
		return nil, e
	}
	trusted := map[string]string{}
	for _, m := range response.Members {
		if m.ID == response.User.ID || m.ID == response.Vault.Owner {
			trusted[m.ID] = m.Fingerprint
		}
	}
	return New(Credentials{base, response.Token, response.User.ID, response.Vault.ID, encode(private.Bytes()), body["publicKey"], trusted})
}
func (c *Client) Info(ctx context.Context) (Info, error) {
	var info Info
	e := c.api(ctx, "/api/sessions/"+c.creds.Session, "GET", nil, &info)
	if e != nil {
		return info, e
	}
	for _, m := range info.Members {
		if m.ID == c.creds.Participant && !m.Revoked {
			if m.PublicKey != encode(c.private.PublicKey().Bytes()) {
				return info, errors.New("credential encryption key mismatch")
			}
			return info, nil
		}
	}
	return info, errors.New("credential is no longer a vault member")
}
func (c *Client) trusted(m Member) bool {
	return m.ID == c.creds.Participant || c.creds.TrustedKeys[m.ID] == m.Fingerprint
}

// Trust requires an independently compared fingerprint. Save a new file to persist.
func (c *Client) Trust(ctx context.Context, participant, fingerprint string) error {
	info, e := c.Info(ctx)
	if e != nil {
		return e
	}
	for _, m := range info.Members {
		if m.ID == participant && !m.Revoked && m.Fingerprint == fingerprint {
			c.creds.TrustedKeys[participant] = fingerprint
			return nil
		}
	}
	return errors.New("fingerprint does not match")
}
func ValidSubject(value string, subscription bool) bool {
	if value == "" || len([]rune(value)) > 160 {
		return false
	}
	for _, r := range value {
		if unicode.IsSpace(r) || r < 32 || r == 127 {
			return false
		}
	}
	parts := strings.Split(value, ".")
	for i, p := range parts {
		if p == "" {
			return false
		}
		if strings.ContainsAny(p, "*>") && !(subscription && (p == "*" || (p == ">" && i == len(parts)-1))) {
			return false
		}
	}
	return true
}
func MatchesSubject(pattern, subject string) bool {
	if !ValidSubject(pattern, true) {
		return false
	}
	p, s := strings.Split(pattern, "."), strings.Split(subject, ".")
	for i, t := range p {
		if t == ">" {
			return i < len(s)
		}
		if i >= len(s) || (t != "*" && t != s[i]) {
			return false
		}
	}
	return len(p) == len(s)
}
func aad(e Envelope) string {
	return fmt.Sprintf("1|%s|%s|%s|%s|%d", e.Session, e.Sender, e.ID, e.Kind, e.Created)
}
func wrapping(private *ecdh.PrivateKey, public string) (cipher.AEAD, error) {
	raw, e := decode(public)
	if e != nil {
		return nil, e
	}
	pub, e := ecdh.P256().NewPublicKey(raw)
	if e != nil {
		return nil, e
	}
	shared, e := private.ECDH(pub)
	if e != nil {
		return nil, e
	}
	key := sha256.Sum256(shared)
	block, e := aes.NewCipher(key[:])
	if e != nil {
		return nil, e
	}
	return cipher.NewGCM(block)
}
func box(key cipher.AEAD, plain []byte, context string) (Box, error) {
	nonce := make([]byte, key.NonceSize())
	if _, e := rand.Read(nonce); e != nil {
		return Box{}, e
	}
	return Box{encode(nonce), encode(key.Seal(nil, nonce, plain, []byte(context)))}, nil
}
func unbox(key cipher.AEAD, b Box, context string) ([]byte, error) {
	nonce, e := decode(b.Nonce)
	if e != nil {
		return nil, e
	}
	data, e := decode(b.Ciphertext)
	if e != nil {
		return nil, e
	}
	if len(nonce) != key.NonceSize() {
		return nil, errors.New("invalid encryption nonce")
	}
	return key.Open(nil, nonce, data, []byte(context))
}
func encrypt(private *ecdh.PrivateKey, sender, vault string, plain []byte, members []Member) (Envelope, error) {
	env := Envelope{V: 1, ID: randomID(), Session: vault, Sender: sender, Kind: "text", Created: time.Now().UnixMilli(), Keys: map[string]Box{}}
	raw := make([]byte, 32)
	if _, e := rand.Read(raw); e != nil {
		return env, e
	}
	block, e := aes.NewCipher(raw)
	if e != nil {
		return env, e
	}
	key, e := cipher.NewGCM(block)
	if e != nil {
		return env, e
	}
	b, e := box(key, plain, aad(env))
	if e != nil {
		return env, e
	}
	env.Nonce, env.Ciphertext = b.Nonce, b.Ciphertext
	for _, m := range members {
		k, e := wrapping(private, m.PublicKey)
		if e != nil {
			return env, e
		}
		wrapped, e := box(k, raw, aad(env)+"|"+m.ID)
		if e != nil {
			return env, e
		}
		env.Keys[m.ID] = wrapped
	}
	return env, nil
}
func decrypt(private *ecdh.PrivateKey, recipient, public string, env Envelope) ([]byte, error) {
	k, e := wrapping(private, public)
	if e != nil {
		return nil, e
	}
	wrapped, ok := env.Keys[recipient]
	if !ok {
		return nil, errors.New("message is for another recipient")
	}
	raw, e := unbox(k, wrapped, aad(env)+"|"+recipient)
	if e != nil {
		return nil, e
	}
	block, e := aes.NewCipher(raw)
	if e != nil {
		return nil, e
	}
	key, e := cipher.NewGCM(block)
	if e != nil {
		return nil, e
	}
	return unbox(key, Box{env.Nonce, env.Ciphertext}, aad(env))
}
func normalizeTags(tags []string) []string {
	out := []string{}
	seen := map[string]bool{}
	for _, t := range tags {
		t = strings.ToLower(strings.TrimPrefix(strings.TrimSpace(t), "#"))
		r := []rune(t)
		if len(r) > 32 {
			t = string(r[:32])
		}
		if t != "" && !seen[t] {
			out = append(out, t)
			seen[t] = true
		}
		if len(out) == 12 {
			break
		}
	}
	return out
}

// Publish creates a new message. nil recipients means every active verified member.
func (c *Client) Publish(ctx context.Context, subject, text string, tags, to []string) (Published, error) {
	var sent Published
	if !ValidSubject(subject, false) || strings.TrimSpace(text) == "" {
		return sent, errors.New("provide a concrete subject and message text")
	}
	info, e := c.Info(ctx)
	if e != nil {
		return sent, e
	}
	wanted := map[string]bool{}
	if to != nil {
		for _, id := range to {
			wanted[id] = true
		}
		wanted[c.creds.Participant] = true
		wanted[info.Owner] = true
	}
	members := []Member{}
	found := map[string]bool{}
	write := false
	for _, m := range info.Members {
		if m.ID == c.creds.Participant {
			write = m.Write
		}
		if !m.Revoked && (to == nil || wanted[m.ID]) {
			if !c.trusted(m) {
				return sent, errors.New("verify recipient fingerprints before sharing")
			}
			members = append(members, m)
			found[m.ID] = true
		}
	}
	if !write {
		return sent, errors.New("read-only credential")
	}
	for id := range wanted {
		if !found[id] {
			return sent, errors.New("recipient is not an active member")
		}
	}
	publisher := c.Publisher
	publisher.Computer = truncate(publisher.Computer, 120)
	publisher.AgentType = truncate(publisher.AgentType, 120)
	publisher.SessionName = truncate(publisher.SessionName, 120)
	publisher.SessionID = truncate(publisher.SessionID, 120)
	data := Message{Format: "ring29.snippet.v1", Version: 1, RecordType: "snippet", SnippetID: randomID(), Title: truncate(strings.SplitN(text, "\n", 2)[0], 80), Text: text, Tags: normalizeTags(tags), Subject: subject, Stream: subject, MessageType: "publish", Publisher: publisher}
	plain, e := json.Marshal(data)
	if e != nil {
		return sent, e
	}
	if len(plain) > 262144 {
		return sent, errors.New("message exceeds 256 KiB")
	}
	env, e := encrypt(c.private, c.creds.Participant, c.creds.Session, plain, members)
	if e != nil {
		return sent, e
	}
	e = c.api(ctx, "/api/sessions/"+c.creds.Session+"/events", "POST", env, &sent)
	sent.SnippetID, sent.Subject = data.SnippetID, subject
	return sent, e
}
func truncate(s string, n int) string {
	r := []rune(strings.TrimSpace(s))
	if len(r) > n {
		r = r[:n]
	}
	return string(r)
}
func (c *Client) Introduce(ctx context.Context) (Published, error) {
	return c.Publish(ctx, "agents.presence", c.Publisher.Computer+" · "+c.Publisher.AgentType+" · "+c.Publisher.SessionName, []string{"introduction"}, nil)
}

// Read returns one batch. Process before saving Cursor; drain until it stops.
// Replay from zero after verifying unknown senders or changing subject/tag filters.
func (c *Client) Read(ctx context.Context, after uint64, subject, tag string) (Batch, error) {
	out := Batch{Updates: []Update{}}
	if after > 9007199254740991 || !ValidSubject(subject, true) {
		return out, errors.New("invalid cursor or subject filter")
	}
	info, e := c.Info(ctx)
	if e != nil {
		return out, e
	}
	members := map[string]Member{}
	for _, m := range info.Members {
		members[m.ID] = m
	}
	var batch struct {
		Events []Envelope `json:"events"`
		Cursor uint64     `json:"cursor"`
	}
	if e = c.api(ctx, "/api/sessions/"+c.creds.Session+"/events?after="+strconv.FormatUint(after, 10), "GET", nil, &batch); e != nil {
		return out, e
	}
	for _, env := range batch.Events {
		if _, ok := env.Keys[c.creds.Participant]; !ok {
			continue
		}
		m, ok := members[env.Sender]
		u := Update{ID: env.ID, Sequence: env.Sequence, Sender: env.Sender, UntrustedContent: true}
		if !ok || !c.trusted(m) {
			u.Fingerprint = m.Fingerprint
			out.Updates = append(out.Updates, u)
			continue
		}
		full := env
		if env.Object {
			if e = c.api(ctx, "/api/sessions/"+c.creds.Session+"/objects/"+env.ID, "GET", nil, &full); e != nil {
				return out, e
			}
		}
		plain, e := decrypt(c.private, c.creds.Participant, m.PublicKey, full)
		if e != nil {
			return out, e
		}
		var data Message
		if json.Unmarshal(plain, &data) != nil || data.Format != "ring29.snippet.v1" {
			data = Message{Text: string(plain), Subject: "general", Tags: []string{}}
		}
		if data.Subject == "" {
			data.Subject = data.Stream
		}
		if data.Subject == "" {
			data.Subject = "general"
		}
		tagMatch := tag == ""
		for _, t := range data.Tags {
			if t == tag {
				tagMatch = true
			}
		}
		if MatchesSubject(subject, data.Subject) && tagMatch {
			u.Trusted = true
			u.Data = &data
			out.Updates = append(out.Updates, u)
		}
	}
	out.Cursor = batch.Cursor
	return out, nil
}
