package main

import (
	"context"
	"database/sql"
	"encoding/base64"
	"encoding/json"
	"flag"
	"fmt"
	"os"
	"strings"
	"syscall"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jackc/pgx/v5/pgxpool"

	"archivmail/config"
)

// checkResult holds the outcome of a single health check.
type checkResult struct {
	Name    string `json:"name"`
	OK      bool   `json:"ok"`
	Detail  string `json:"detail"`
	Latency string `json:"latency,omitempty"`
}

// runStatus performs health checks against PostgreSQL, Manticore Search, and
// the mail storage directory, and prints a summary.
// Usage: archivmail status [-config /path/to/config.yml] [-json]
func runStatus(args []string) {
	fs := flag.NewFlagSet("status", flag.ExitOnError)
	configPath := fs.String("config", "/etc/archivmail/config.yml", "path to config file")
	jsonOut := fs.Bool("json", false, "machine-readable JSON output")
	fs.Parse(args)

	cfg, err := config.Load(*configPath)
	if err != nil {
		fmt.Fprintf(os.Stderr, "archivmail status: config laden fehlgeschlagen: %v\n", err)
		os.Exit(1)
	}

	results := []checkResult{
		checkPostgres(cfg),
		checkManticore(cfg),
		checkStorage(cfg),
		checkEncryption(cfg),
		checkAuditLog(cfg),
		checkRetention(cfg),
	}

	allOK := true
	for _, r := range results {
		if !r.OK {
			allOK = false
		}
	}

	if *jsonOut {
		enc := json.NewEncoder(os.Stdout)
		enc.SetIndent("", "  ")
		_ = enc.Encode(map[string]interface{}{"ok": allOK, "checks": results})
	} else {
		for _, r := range results {
			status := "OK"
			if !r.OK {
				status = "FEHLER"
			} else if strings.HasPrefix(r.Detail, "WARNUNG") {
				// Non-fatal but GoBD-relevant (e.g. PROJ-51 retention check):
				// reflect the warning in the status label without affecting
				// the exit code (r.OK stays true).
				status = "WARN"
			}
			if r.Latency != "" {
				fmt.Printf("[%-6s] %-12s %s (%s)\n", status, r.Name, r.Detail, r.Latency)
			} else {
				fmt.Printf("[%-6s] %-12s %s\n", status, r.Name, r.Detail)
			}
		}
	}

	if !allOK {
		os.Exit(1)
	}
}

func checkPostgres(cfg *config.Config) checkResult {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	start := time.Now()
	pool, err := pgxpool.New(ctx, cfg.Database.DSN())
	if err != nil {
		return checkResult{Name: "PostgreSQL", OK: false, Detail: fmt.Sprintf("Verbindung fehlgeschlagen: %v", err)}
	}
	defer pool.Close()

	if err := pool.Ping(ctx); err != nil {
		return checkResult{Name: "PostgreSQL", OK: false, Detail: fmt.Sprintf("Ping fehlgeschlagen: %v", err)}
	}
	latency := time.Since(start)

	var totalMails int64
	var firstMail, lastMail *time.Time
	_ = pool.QueryRow(ctx, `SELECT COUNT(*), MIN(received_at), MAX(received_at) FROM emails`).
		Scan(&totalMails, &firstMail, &lastMail)

	detail := fmt.Sprintf("%d Mails", totalMails)
	if firstMail != nil && lastMail != nil {
		detail += fmt.Sprintf(", erste %s, letzte %s", firstMail.Format("2006-01-02"), lastMail.Format("2006-01-02 15:04"))
	}
	return checkResult{Name: "PostgreSQL", OK: true, Detail: detail, Latency: latency.Round(time.Millisecond).String()}
}

func checkManticore(cfg *config.Config) checkResult {
	dsn := cfg.Index.ManticoreDSN
	if dsn == "" {
		dsn = "manticore@tcp(127.0.0.1:9306)/?charset=utf8mb4"
	}

	start := time.Now()
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		return checkResult{Name: "Manticore", OK: false, Detail: fmt.Sprintf("Verbindung fehlgeschlagen: %v", err)}
	}
	defer db.Close()

	if err := db.Ping(); err != nil {
		return checkResult{Name: "Manticore", OK: false, Detail: fmt.Sprintf("Ping fehlgeschlagen: %v", err)}
	}
	latency := time.Since(start)

	var version string
	_ = db.QueryRow(`SHOW STATUS LIKE 'version'`).Scan(new(string), &version)

	detail := "erreichbar"
	if version != "" {
		detail = "Version " + version
	}
	return checkResult{Name: "Manticore", OK: true, Detail: detail, Latency: latency.Round(time.Millisecond).String()}
}

func checkStorage(cfg *config.Config) checkResult {
	keyfile := cfg.Storage.Keyfile
	data, err := os.ReadFile(keyfile)
	if err != nil {
		return checkResult{Name: "Storage", OK: false, Detail: fmt.Sprintf("Keyfile %s nicht lesbar: %v", keyfile, err)}
	}
	raw := strings.TrimSpace(string(data))
	decoded, err := base64.StdEncoding.DecodeString(raw)
	if err != nil {
		decoded = []byte(raw)
	}
	if len(decoded) != 32 {
		return checkResult{Name: "Storage", OK: false, Detail: fmt.Sprintf("Keyfile %s ergibt %d Bytes, erwartet 32", keyfile, len(decoded))}
	}

	storePath := cfg.Storage.StorePath
	if _, err := os.Stat(storePath); err != nil {
		return checkResult{Name: "Storage", OK: false, Detail: fmt.Sprintf("store_path %s nicht erreichbar: %v", storePath, err)}
	}

	var stat syscall.Statfs_t
	if err := syscall.Statfs(storePath, &stat); err != nil {
		return checkResult{Name: "Storage", OK: false, Detail: fmt.Sprintf("Statfs %s fehlgeschlagen: %v", storePath, err)}
	}
	total := stat.Blocks * uint64(stat.Bsize)
	free := stat.Bavail * uint64(stat.Bsize)
	var usedPct float64
	if total > 0 {
		usedPct = (1 - float64(free)/float64(total)) * 100
	}

	detail := fmt.Sprintf("%s, %.1f%% belegt, %s frei", storePath, usedPct, formatBytes(free))
	ok := usedPct < 95
	if !ok {
		detail += " — Speicherplatz kritisch knapp"
	}
	return checkResult{Name: "Storage", OK: ok, Detail: detail}
}

// checkEncryption reports whether at-rest AES-256-GCM encryption is active
// (PROJ-49). A configured, readable 32-byte keyfile yields status "enabled";
// everything else yields "disabled" with a concrete reason. Disabled is NOT a
// hard error (backwards-compatible, see PROJ-49) — the entry stays OK=true so
// existing unencrypted installations keep a zero exit code, but the detail
// makes the GoBD-relevant state clearly visible.
func checkEncryption(cfg *config.Config) checkResult {
	keyfile := strings.TrimSpace(cfg.Storage.Keyfile)
	if keyfile == "" {
		return checkResult{Name: "Encryption", OK: true,
			Detail: "disabled — kein storage.keyfile gesetzt, Speicher NICHT AES-256-verschlüsselt"}
	}

	data, err := os.ReadFile(keyfile)
	if err != nil {
		return checkResult{Name: "Encryption", OK: true,
			Detail: fmt.Sprintf("disabled — Keyfile %s nicht lesbar: %v", keyfile, err)}
	}
	raw := strings.TrimSpace(string(data))
	decoded, derr := base64.StdEncoding.DecodeString(raw)
	if derr != nil {
		decoded = []byte(raw)
	}
	if len(decoded) != 32 {
		return checkResult{Name: "Encryption", OK: true,
			Detail: fmt.Sprintf("disabled — ungültiges Keyfile %s (%d Byte, erwartet 32)", keyfile, len(decoded))}
	}

	return checkResult{Name: "Encryption", OK: true, Detail: fmt.Sprintf("enabled — AES-256-GCM (%s)", keyfile)}
}

// checkAuditLog verifies that the append-only audit log file (PROJ-48) exists
// and is writable. It performs a non-destructive O_APPEND open without writing
// any bytes, so the immutability of existing content is not affected.
func checkAuditLog(cfg *config.Config) checkResult {
	path := cfg.Audit.ResolvedLogPath()

	f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0o640)
	if err != nil {
		if os.IsNotExist(err) {
			return checkResult{Name: "Audit-Log", OK: false, Detail: fmt.Sprintf("%s existiert nicht", path)}
		}
		return checkResult{Name: "Audit-Log", OK: false, Detail: fmt.Sprintf("%s nicht beschreibbar: %v", path, err)}
	}
	defer f.Close()

	detail := path + ", beschreibbar"
	if fi, statErr := f.Stat(); statErr == nil {
		detail = fmt.Sprintf("%s, beschreibbar, %s", path, formatBytes(uint64(fi.Size())))
	}
	return checkResult{Name: "Audit-Log", OK: true, Detail: detail}
}

// checkRetention warns (PROJ-51) when effectively no deletion lock is active:
// global retention_days = 0 AND min_retention_days = 0 AND no tenant with
// retention_days > 0 AND no archiving rule carrying a retention_days value.
// Like the encryption check it never reports a hard error (OK stays true), it
// only surfaces the GoBD-relevant state in the detail text.
func checkRetention(cfg *config.Config) checkResult {
	global := cfg.Storage.RetentionDays
	minRet := cfg.Storage.MinRetentionDays
	if global > 0 || minRet > 0 {
		return checkResult{Name: "Retention", OK: true,
			Detail: fmt.Sprintf("Löschsperre aktiv (global=%d Tage, min=%d Tage)", global, minRet)}
	}

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	pool, err := pgxpool.New(ctx, cfg.Database.DSN())
	if err != nil {
		return checkResult{Name: "Retention", OK: true,
			Detail: "DB nicht erreichbar — Tenant-/Regel-Aufbewahrung nicht prüfbar"}
	}
	defer pool.Close()

	var tenantLocks, ruleLocks int
	_ = pool.QueryRow(ctx, `SELECT COUNT(*) FROM tenants WHERE retention_days > 0`).Scan(&tenantLocks)
	_ = pool.QueryRow(ctx, `SELECT COUNT(*) FROM archiving_rules WHERE retention_days IS NOT NULL`).Scan(&ruleLocks)

	if tenantLocks > 0 || ruleLocks > 0 {
		return checkResult{Name: "Retention", OK: true,
			Detail: fmt.Sprintf("Löschsperre aktiv (%d Mandant(en), %d Regel(n) mit Aufbewahrung)", tenantLocks, ruleLocks)}
	}

	return checkResult{Name: "Retention", OK: true,
		Detail: "WARNUNG — keine Löschsperre aktiv: retention_days=0, min_retention_days=0, keine Mandanten-/Regel-Aufbewahrung (GoBD-relevant)"}
}

func formatBytes(b uint64) string {
	const unit = 1024
	if b < unit {
		return fmt.Sprintf("%d B", b)
	}
	div, exp := uint64(unit), 0
	for n := b / unit; n >= unit; n /= unit {
		div *= unit
		exp++
	}
	return fmt.Sprintf("%.1f %ciB", float64(b)/float64(div), "KMGTPE"[exp])
}
