summaryrefslogtreecommitdiffstats
path: root/internal/formatter/usage.go
blob: 6732a3b6cf9be15d3def8a377d6392a40cf6d5c9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package formatter

import (
	"fmt"
	"strings"
	"time"

	"git.db.org.ai/dborg/internal/models"
)

// FormatCreditUsageLogs renders raw credit_usage_log rows.
func FormatCreditUsageLogs(resp *models.CreditUsageLogsResponse, asJSON bool) (string, error) {
	if asJSON {
		if err := PrintColorizedJSON(resp); err != nil {
			return "", err
		}
		return "", nil
	}

	if len(resp.Logs) == 0 {
		return fmt.Sprintf("%s\n", Gray("No usage logs found")), nil
	}

	var sb strings.Builder
	sb.WriteString(fmt.Sprintf("\n%s\n", Bold(Cyan("Credit Usage Logs"))))
	sb.WriteString(fmt.Sprintf("%s\n\n", Gray(strings.Repeat("─", 90))))

	table := NewTable([]string{"ID", "Account", "Endpoint", "Path", "Cost", "Charged", "Status", "Time"})

	for _, row := range resp.Logs {
		statusStr := Green(fmt.Sprintf("%d", row.StatusCode))
		if row.StatusCode >= 400 {
			statusStr = Red(fmt.Sprintf("%d", row.StatusCode))
		} else if row.StatusCode >= 300 {
			statusStr = Yellow(fmt.Sprintf("%d", row.StatusCode))
		}

		chargedStr := Gray("0")
		if row.CreditsCharged > 0 {
			chargedStr = Yellow(fmt.Sprintf("%d", row.CreditsCharged))
		}

		timeStr := row.CreatedAt
		if t, err := time.Parse(time.RFC3339, row.CreatedAt); err == nil {
			timeStr = t.Format("01-02 15:04:05")
		} else if t, err := time.Parse("2006-01-02T15:04:05Z", row.CreatedAt); err == nil {
			timeStr = t.Format("01-02 15:04:05")
		}

		table.AddRow(
			Gray(fmt.Sprintf("%d", row.ID)),
			Bold(row.AccountName),
			Cyan(row.Endpoint),
			Dim(truncate(row.Path, 30)),
			Gray(fmt.Sprintf("%d", row.EndpointCost)),
			chargedStr,
			statusStr,
			Gray(timeStr),
		)
	}

	sb.WriteString(table.Render())
	sb.WriteString(fmt.Sprintf("\n%s %d rows\n", Blue("Total:"), resp.Count))
	return sb.String(), nil
}

// FormatCreditUsageByEndpoint renders per-endpoint aggregate stats.
func FormatCreditUsageByEndpoint(resp *models.CreditUsageByEndpointResponse, asJSON bool) (string, error) {
	if asJSON {
		if err := PrintColorizedJSON(resp); err != nil {
			return "", err
		}
		return "", nil
	}

	if len(resp.Endpoints) == 0 {
		return fmt.Sprintf("%s\n", Gray("No endpoint usage data found")), nil
	}

	fromStr, toStr := formatTimeRange(resp.From, resp.To)

	var sb strings.Builder
	sb.WriteString(fmt.Sprintf("\n%s\n", Bold(Cyan("Usage by Endpoint"))))
	sb.WriteString(fmt.Sprintf("%s  %s → %s\n\n", Gray(strings.Repeat("─", 60)), Gray(fromStr), Gray(toStr)))

	table := NewTable([]string{"Endpoint", "Total", "Success", "Cost", "Charged"})

	var totalCalls, totalCharged int64
	for _, row := range resp.Endpoints {
		successRate := ""
		if row.TotalCalls > 0 {
			pct := float64(row.SuccessCalls) / float64(row.TotalCalls) * 100
			color := Green
			if pct < 50 {
				color = Red
			} else if pct < 80 {
				color = Yellow
			}
			successRate = color(fmt.Sprintf("%d (%.0f%%)", row.SuccessCalls, pct))
		}

		chargedStr := Gray("0")
		if row.TotalCharged > 0 {
			chargedStr = Yellow(fmt.Sprintf("%d", row.TotalCharged))
		}

		table.AddRow(
			Cyan(row.Endpoint),
			Bold(fmt.Sprintf("%d", row.TotalCalls)),
			successRate,
			Gray(fmt.Sprintf("%d ea", row.EndpointCost)),
			chargedStr,
		)
		totalCalls += row.TotalCalls
		totalCharged += row.TotalCharged
	}

	sb.WriteString(table.Render())
	sb.WriteString(fmt.Sprintf("\n%s %d calls   %s %d credits charged\n",
		Blue("Total calls:"), totalCalls,
		Blue("Total charged:"), totalCharged,
	))
	return sb.String(), nil
}

// FormatCreditUsageByAccount renders per-account per-endpoint aggregate stats.
func FormatCreditUsageByAccount(resp *models.CreditUsageByAccountResponse, asJSON bool) (string, error) {
	if asJSON {
		if err := PrintColorizedJSON(resp); err != nil {
			return "", err
		}
		return "", nil
	}

	if len(resp.Accounts) == 0 {
		return fmt.Sprintf("%s\n", Gray("No account usage data found")), nil
	}

	fromStr, toStr := formatTimeRange(resp.From, resp.To)

	var sb strings.Builder
	sb.WriteString(fmt.Sprintf("\n%s\n", Bold(Cyan("Usage by Account"))))
	sb.WriteString(fmt.Sprintf("%s  %s → %s\n\n", Gray(strings.Repeat("─", 60)), Gray(fromStr), Gray(toStr)))

	table := NewTable([]string{"Account", "Endpoint", "Calls", "Charged", "Last Call"})

	// Group consecutive rows by account for visual separation
	var prevAccount string
	var totalCalls, totalCharged int64
	for _, row := range resp.Accounts {
		nameStr := Bold(row.AccountName)
		if row.AccountName == prevAccount {
			nameStr = Dim("  ↳")
		}
		prevAccount = row.AccountName

		chargedStr := Gray("0")
		if row.TotalCharged > 0 {
			chargedStr = Yellow(fmt.Sprintf("%d", row.TotalCharged))
		}

		lastCall := row.LastCall
		if t, err := time.Parse("2006-01-02 15:04:05", row.LastCall); err == nil {
			lastCall = t.Format("2006-01-02 15:04")
		}

		table.AddRow(
			nameStr,
			Cyan(row.Endpoint),
			fmt.Sprintf("%d", row.TotalCalls),
			chargedStr,
			Gray(lastCall),
		)
		totalCalls += row.TotalCalls
		totalCharged += row.TotalCharged
	}

	sb.WriteString(table.Render())
	sb.WriteString(fmt.Sprintf("\n%s %d   %s %d credits charged\n",
		Blue("Total calls:"), totalCalls,
		Blue("Total charged:"), totalCharged,
	))
	return sb.String(), nil
}

func formatTimeRange(from, to string) (string, string) {
	fromStr, toStr := from, to
	if t, err := time.Parse(time.RFC3339, from); err == nil {
		fromStr = t.Format("2006-01-02 15:04")
	}
	if t, err := time.Parse(time.RFC3339, to); err == nil {
		toStr = t.Format("2006-01-02 15:04")
	}
	return fromStr, toStr
}

func truncate(s string, n int) string {
	if len(s) <= n {
		return s
	}
	return s[:n-1] + "…"
}