package main

import (
	"encoding/json"
	"os"
	"path/filepath"
	"testing"
)

func TestWorkedValues(t *testing.T) {
	for _, c := range []struct {
		t, s int
		pct  string
		k    int
	}{
		{0, 0, "50.0%", 8},
		{3, 3, "80.0%", 5},
		{2, 0, "25.0%", 26},
		{10, 7, "66.7%", 28},
		{100, 100, "99.0%", 0},
		{1998, 1998, "99.9%", 0}, // unclamped it would round to 100.0%
		{2998, 0, "0.1%", 26990}, // unclamped it would round to 0.0%
	} {
		if got := pct(c.s, c.t); got != c.pct {
			t.Errorf("pct(s=%d, t=%d) = %s, want %s", c.s, c.t, got, c.pct)
		}
		if got := toNinety(c.s, c.t); got != c.k {
			t.Errorf("toNinety(s=%d, t=%d) = %d, want %d", c.s, c.t, got, c.k)
		}
	}
}

// k must be the smallest number of further yeses that brings the exact
// fraction (s+k+1)/(t+k+2) to 0.9 or more.
func TestToNinetyAgainstExactFraction(t *testing.T) {
	for tr := 0; tr <= 60; tr++ {
		for s := 0; s <= tr; s++ {
			k := toNinety(s, tr)
			reached := 10*(s+k+1) >= 9*(tr+k+2)
			earlier := k > 0 && 10*(s+k) >= 9*(tr+k+1)
			if !reached || earlier {
				t.Fatalf("toNinety(s=%d, t=%d) = %d is not the smallest k", s, tr, k)
			}
		}
	}
}

func TestRender(t *testing.T) {
	var trials []trial
	for range 3 {
		trials = append(trials, trial{"build", true})
	}
	for _, ok := range []bool{true, true, false, true, true, false, true, true, false, true} {
		trials = append(trials, trial{"deploy", ok})
	}
	trials = append(trials, trial{"meeting-on-time", false}, trial{"meeting-on-time", false})

	want := "Tomorrow Table for 2026-10-14\n" +
		"Record: /state/log.jsonl\n" +
		"Method: rule of succession (Laplace, 1814). Each trial counted as independent.\n" +
		"\n" +
		"Event            Trials  Yes  Tomorrow*  To 90%  Last five\n" +
		"build                 3    3      80.0%       5  YYY\n" +
		"deploy               10    7      66.7%      28  NYYNY\n" +
		"meeting-on-time       2    0      25.0%      26  NN\n" +
		"\n" +
		"* No event has been assigned certainty.\n"
	if got := render("2026-10-14", "/state/log.jsonl", trials); got != want {
		t.Errorf("render:\n%s\nwant:\n%s", got, want)
	}

	empty := "Tomorrow Table for 2026-10-14\n" +
		"Record: /state/log.jsonl\n" +
		"Method: rule of succession (Laplace, 1814). Each trial counted as independent.\n" +
		"\n" +
		"Nothing has happened yet. Record something: tomorrow record walk yes\n"
	if got := render("2026-10-14", "/state/log.jsonl", nil); got != empty {
		t.Errorf("empty render:\n%s\nwant:\n%s", got, empty)
	}
}

func TestParseLine(t *testing.T) {
	valid := map[string]trial{
		`{"at":"2026-10-13T09:12:03Z","event":"build","ok":true,"how":"run","ms":4210}`: {"build", true},
		`{"event":"a.b_c-9","ok":false}`:                                                {"a.b_c-9", false},
	}
	for line, want := range valid {
		if got, ok := parseLine(line); !ok || got != want {
			t.Errorf("parseLine(%s) = %v, %v; want %v", line, got, ok, want)
		}
	}
	for _, line := range []string{
		``, `not json`, `null`, `[]`, `"build"`,
		`{"event":"build"}`,
		`{"ok":true}`,
		`{"event":"build","ok":"true"}`,
		`{"event":"build","ok":null}`,
		`{"event":7,"ok":true}`,
		`{"event":"Build","ok":true}`,
		`{"Event":"build","OK":true}`,
		`{"event":"build","ok":true} {}`,
	} {
		if _, ok := parseLine(line); ok {
			t.Errorf("parseLine(%s) accepted", line)
		}
	}
}

func TestValidName(t *testing.T) {
	for name, want := range map[string]bool{
		"build": true, "meeting-on-time": true, "v1.2_x": true, "0": true,
		"abcdefghijklmnopqrstuvwx": true, "abcdefghijklmnopqrstuvwxy": false,
		"": false, ".hidden": false, "-x": false, "Build": false, "a b": false, "Build!": false,
	} {
		if validName(name) != want {
			t.Errorf("validName(%q) != %v", name, want)
		}
	}
}

func TestEntryEncoding(t *testing.T) {
	zero := int64(0)
	for e, want := range map[entry]string{
		{"2026-10-13T09:12:03Z", "build", true, "run", &zero}:          `{"at":"2026-10-13T09:12:03Z","event":"build","ok":true,"how":"run","ms":0}`,
		{"2026-10-13T09:15:40Z", "meeting-on-time", true, "hand", nil}: `{"at":"2026-10-13T09:15:40Z","event":"meeting-on-time","ok":true,"how":"hand"}`,
	} {
		b, err := json.Marshal(e)
		if err != nil || string(b) != want {
			t.Errorf("marshal = %s, %v; want %s", b, err, want)
		}
	}
}

// A hand edit that drops the final newline must not cost the next record.
func TestAppendAfterHandEdit(t *testing.T) {
	path := filepath.Join(t.TempDir(), "state", "log.jsonl")
	if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(path, []byte(`{"event":"walk","ok":true}`), 0o600); err != nil {
		t.Fatal(err)
	}
	if err := appendEntry(path, entry{"2026-10-13T09:15:40Z", "walk", false, "hand", nil}); err != nil {
		t.Fatal(err)
	}
	trials, skipped, err := load(path)
	if err != nil || skipped != 0 || len(trials) != 2 || trials[0] != (trial{"walk", true}) || trials[1] != (trial{"walk", false}) {
		t.Errorf("load = %v, %d, %v", trials, skipped, err)
	}
}
