package config

import (
	"errors"
	"fmt"
	"net/url"
	"os"
	"strings"

	"github.com/knadh/koanf/parsers/yaml"
	"github.com/knadh/koanf/providers/env/v2"
	"github.com/knadh/koanf/providers/file"
	"github.com/knadh/koanf/v2"
)

// errAPNsHalfConfig is returned when some but not all APNs fields are set.
var errAPNsHalfConfig = errors.New(
	"CDROP_APNS_KEY_PATH, CDROP_APNS_KEY_ID, CDROP_APNS_TEAM_ID, and CDROP_APNS_TOPIC " +
		"must all be set together, or none at all (partial config is always an operator error)")

const envPrefix = "CDROP_"

type Config struct {
	AuthMode string `koanf:"auth_mode"`
	DevToken string `koanf:"dev_token"`

	DBPath string `koanf:"db_path"`
	Listen string `koanf:"listen"`

	// DeviceTTLHours is the maximum age of a row in `devices` before the
	// background sweeper deletes it. Brief §2 sets the refresh_token sliding
	// window at 196h (≈8 days) — devices must not outlive that. Default 196h.
	DeviceTTLHours int `koanf:"device_ttl_hours"`

	// PublicURL 是部署的公开源（scheme://host），如 https://drop.commilitia.net。
	// 用于拼扫码登录的 QR 链接、作 Web Push 的默认联系标识。dev 留空时回退到请求自身
	// 的 Host。
	PublicURL string `koanf:"public_url"`

	// Auth Broker 接入（路径 A）。cdrop 把身份与会话生命周期委托给 broker：每个受控
	// 请求在边缘由 broker /verify（经 Caddy）鉴权并注入 X-Auth-* 头，cdrop 直接信任；
	// 扫码批准时经 broker 内部 API 委托签发会话，cdrop 不再自签。
	//   BrokerBaseURL     —— broker 内网地址（如 http://broker-internal-ip:8080），在 docker
	//                        内网直连（绝不经公网反代，以保 /internal/* 与 /refresh 可达）。
	//   BrokerInternalKey —— broker /internal/* 端点的共享密钥（作 X-Internal-Key 发送），
	//                        prod 必填。
	//   BrokerApp         —— 本应用在 broker apps 注册表里的 key（默认 "cdrop"）。
	BrokerBaseURL     string `koanf:"broker_base_url"`
	BrokerInternalKey string `koanf:"broker_internal_key"`
	BrokerApp         string `koanf:"broker_app"`

	// BrokerPublicURL is the broker's PUBLIC origin (e.g. https://sso.commilitia.net)
	// — where a browser is sent to log in via global SSO. Distinct from BrokerBaseURL
	// (the internal address cdrop's server-to-server calls use). GET /api/auth/login
	// 302-redirects here; empty disables that redirect (native-only deployments).
	BrokerPublicURL string `koanf:"broker_public_url"`

	// 按档令牌 TTL（秒）：cdrop 经 broker 委托签发会话时请求的 access / refresh 寿命。
	// full＝可信设备（access 短、refresh 一周、滑动）；guest＝扫码借用（同样的短 access、
	// refresh 一天）。两档都在 broker 的 app 上限内（access 3600 / refresh 604800），
	// clampTTL 不会压它们。broker /verify 每请求查活，短 access 只决定续期频率、不影响
	// 吊销即时性。
	FullAccessTTLSeconds   int `koanf:"full_access_ttl_seconds"`
	FullRefreshTTLSeconds  int `koanf:"full_refresh_ttl_seconds"`
	GuestAccessTTLSeconds  int `koanf:"guest_access_ttl_seconds"`
	GuestRefreshTTLSeconds int `koanf:"guest_refresh_ttl_seconds"`

	// Cloudflare Realtime TURN (https://developers.cloudflare.com/realtime/turn/).
	// When both fields are set, /api/calls/credentials returns short-lived
	// TLS-capable TURN creds (turns:turn.cloudflare.com:5349); otherwise the
	// endpoint serves a STUN-only fallback so dev / no-CF deploys still work.
	CFTurnKeyID    string `koanf:"cf_turn_key_id"`
	CFTurnAPIToken string `koanf:"cf_turn_api_token"`

	// Clipboard：单条覆写式同步。MaxBytes 限制单次写入字节数；DebounceSec 是
	// 收到 PUT 后等待"无新写入稳定窗口"的秒数，到期才广播 SSE。同窗口内的
	// 后续 PUT 直接刷新 generation 让旧广播取消。
	ClipboardMaxBytes    int `koanf:"clipboard_max_bytes"`
	ClipboardDebounceSec int `koanf:"clipboard_debounce_sec"`
	// ClipboardTTLSec 是云剪贴板内容的存活秒数。因为无法可靠区分密码与普通
	// 文本（密码.app / 浏览器扩展复制都不打敏感标记），改以短 TTL 限制暴露面：
	// 内容超过 TTL 后 GET 返回空，后台 sweeper 亦清除其 content。0 = 不过期。
	ClipboardTTLSec int `koanf:"clipboard_ttl_sec"`

	// Web Push (RFC 8291/8292)：浏览器 / PWA 在页面关闭时仍能收到系统通知。
	// 公私钥是自签的 VAPID 密钥对（与 Apple/Google 账号无关），用 `just vapid-keygen`
	// 生成一次后固定——更换会使所有既有订阅失效。两者皆设才启用推送，缺一即整体
	// 关闭（订阅端点返回 503，事件回退为「仅在线设备收 SSE」）。Subject 是 VAPID
	// 要求的联系标识（mailto: 或站点 URL）；留空时回退为部署站点 URL。
	VAPIDPublicKey  string `koanf:"vapid_public_key"`
	VAPIDPrivateKey string `koanf:"vapid_private_key"`
	VAPIDSubject    string `koanf:"vapid_subject"`

	// APNs (Apple Push Notification service): iOS device push channel.
	// All four fields must be set together or none (partial config is an error).
	//   APNSKeyPath  — filesystem path to the .p8 (PEM PKCS8 ES256) key Apple issues.
	//   APNSKeyID    — the 10-character Key ID from the Apple Developer portal.
	//   APNSTeamID   — the 10-character Team ID from the Apple Developer portal.
	//   APNSTopic    — the app bundle ID (e.g. "net.commilitia.cdrop").
	//   APNSEnv      — "prod" (default) or "sandbox" (dev/TestFlight builds).
	// When unset, APNs is disabled and the register endpoint returns 503.
	APNSKeyPath string `koanf:"apns_key_path"`
	APNSKeyID   string `koanf:"apns_key_id"`
	APNSTeamID  string `koanf:"apns_team_id"`
	APNSTopic   string `koanf:"apns_topic"`
	APNSEnv     string `koanf:"apns_env"`

	// apnsKeyPEM is the loaded .p8 file contents, populated by Load() when
	// APNSKeyPath is set. Callers read it via APNSKeyPEM().
	apnsKeyPEM []byte

	// 扫码登录（QR）：新设备出码、已登录设备扫码批准，经 Auth Broker 委托签发会话。
	// QRLoginEnabled 关闭则 /api/auth/qr/* 返回 503。QRRequestTTLSeconds 是一条扫码
	// 请求的存活秒数（默认 120）。批准后铸的会话寿命取上面的按档 TTL（full / guest）。
	QRLoginEnabled      bool `koanf:"qr_login_enabled"`
	QRRequestTTLSeconds int  `koanf:"qr_request_ttl_seconds"`
}

// QRLoginOn reports whether scan-login is enabled and the broker it delegates
// minting to is configured. Without BrokerBaseURL cdrop can't mint a session on
// approval, so QR stays off regardless of the flag.
func (c *Config) QRLoginOn() bool {
	return c.QRLoginEnabled && c.BrokerBaseURL != ""
}

// BrokerAppOrDefault returns the configured broker app key, defaulting to "cdrop".
func (c *Config) BrokerAppOrDefault() string {
	if c.BrokerApp != "" {
		return c.BrokerApp
	}
	return "cdrop"
}

// Load reads config from optional ./config.yaml then overrides with CDROP_* env.
// Validates dev/prod invariants; returns error if invariants are violated.
func Load() (*Config, error) {
	k := koanf.New(".")

	k.Set("auth_mode", "prod")
	k.Set("db_path", "./cdrop.db")
	k.Set("listen", ":8080")
	k.Set("device_ttl_hours", 196)
	k.Set("clipboard_max_bytes", 65536)
	k.Set("clipboard_debounce_sec", 3)
	k.Set("qr_login_enabled", true)
	k.Set("qr_request_ttl_seconds", 120)
	k.Set("broker_app", "cdrop")
	k.Set("full_access_ttl_seconds", 900)
	k.Set("full_refresh_ttl_seconds", 604800)
	k.Set("guest_access_ttl_seconds", 900)
	k.Set("guest_refresh_ttl_seconds", 86400)

	if _, err := os.Stat("config.yaml"); err == nil {
		if err := k.Load(file.Provider("config.yaml"), yaml.Parser()); err != nil {
			return nil, fmt.Errorf("load config.yaml: %w", err)
		}
	}

	envProvider := env.Provider(".", env.Opt{
		Prefix: envPrefix,
		TransformFunc: func(key, value string) (string, any) {
			return strings.ToLower(strings.TrimPrefix(key, envPrefix)), value
		},
	})
	if err := k.Load(envProvider, nil); err != nil {
		return nil, fmt.Errorf("load env: %w", err)
	}

	cfg := &Config{}
	if err := k.Unmarshal("", cfg); err != nil {
		return nil, fmt.Errorf("unmarshal config: %w", err)
	}

	if err := cfg.validate(); err != nil {
		return nil, err
	}

	// Load the APNs .p8 key file after validation (validate() already confirmed
	// that if APNSKeyPath is set, all other APNs fields are also set).
	if cfg.APNSKeyPath != "" {
		pem, err := os.ReadFile(cfg.APNSKeyPath)
		if err != nil {
			return nil, fmt.Errorf("read CDROP_APNS_KEY_PATH %q: %w", cfg.APNSKeyPath, err)
		}
		cfg.apnsKeyPEM = pem
	}

	return cfg, nil
}

func (c *Config) validate() error {
	switch c.AuthMode {
	case "dev":
		if c.DevToken == "" {
			return errors.New("CDROP_AUTH_MODE=dev requires CDROP_DEV_TOKEN; refusing to start")
		}
	case "prod":
		// cdrop delegates identity + session lifecycle to the Auth Broker (path A):
		// without its internal address and shared key, QR-approve can't mint and the
		// service is non-functional. Refuse to boot rather than half-run.
		if c.BrokerBaseURL == "" {
			return errors.New(
				"CDROP_AUTH_MODE=prod requires CDROP_BROKER_BASE_URL " +
					"(the Auth Broker internal address); refusing to start")
		}
		if c.BrokerInternalKey == "" {
			return errors.New(
				"CDROP_AUTH_MODE=prod requires CDROP_BROKER_INTERNAL_KEY " +
					"(shared secret for the broker /internal/* API); refusing to start")
		}
		// PublicURL fixes the deployment origin the CSRF Origin check compares against
		// (deriveSiteOrigin → sameOrigin). Without it sameOrigin fails OPEN, silently
		// disabling the only cdrop-side CSRF guard on the state-changing POST endpoints
		// (device-session mint, logout). Require it in prod so the guard never fails open.
		if c.PublicURL == "" {
			return errors.New(
				"CDROP_AUTH_MODE=prod requires CDROP_PUBLIC_URL " +
					"(the deployment origin, used for the CSRF check); refusing to start")
		}
	default:
		return fmt.Errorf("CDROP_AUTH_MODE must be \"dev\" or \"prod\", got %q", c.AuthMode)
	}

	// Web Push is optional, but a half-configured pair is always an operator
	// mistake: with only one key set, every push send would fail at runtime
	// while the feature looks "on". Fail fast instead of silently degrading.
	if (c.VAPIDPublicKey == "") != (c.VAPIDPrivateKey == "") {
		return errors.New(
			"CDROP_VAPID_PUBLIC_KEY and CDROP_VAPID_PRIVATE_KEY must be set together " +
				"(run `just vapid-keygen`); set neither to disable Web Push")
	}

	// APNs is optional, but partial config is always an operator error: all four
	// fields must be present for APNs to function. Count how many are set; any
	// non-zero count that is not four is a mistake.
	apnsSet := 0
	for _, v := range []string{c.APNSKeyPath, c.APNSKeyID, c.APNSTeamID, c.APNSTopic} {
		if v != "" {
			apnsSet++
		}
	}
	if apnsSet > 0 && apnsSet < 4 {
		return errAPNsHalfConfig
	}

	return nil
}

// APNSKeyPEM returns the loaded .p8 key contents. Empty when APNs is
// unconfigured (APNSKeyPath was not set).
func (c *Config) APNSKeyPEM() []byte { return c.apnsKeyPEM }

// APNSEnabled reports whether all APNs fields are configured.
func (c *Config) APNSEnabled() bool {
	return c.APNSKeyPath != "" && c.APNSKeyID != "" && c.APNSTeamID != "" && c.APNSTopic != ""
}

// PushEnabled reports whether Web Push is configured (both VAPID keys present).
func (c *Config) PushEnabled() bool {
	return c.VAPIDPublicKey != "" && c.VAPIDPrivateKey != ""
}

// VAPIDSubjectOrDefault returns the VAPID contact identity. Push services want a
// way to reach the operator; the configured value wins, else the deployment's
// own origin (derived from the OIDC redirect URI), else the product URL.
func (c *Config) VAPIDSubjectOrDefault() string {
	if c.VAPIDSubject != "" {
		return c.VAPIDSubject
	}
	if u, err := url.Parse(c.PublicURL); err == nil && u.Scheme != "" && u.Host != "" {
		return u.Scheme + "://" + u.Host
	}
	return "https://drop.commilitia.net"
}
