package status

import (
	"context"
	"fmt"
	"os"
	"path/filepath"
	"testing"
	"time"
)

func TestCodexCheckerSkipsUpdatePromptBeforeStatus(t *testing.T) {
	dir := t.TempDir()
	fakeCodex := filepath.Join(dir, "codex")
	script := `#!/usr/bin/env sh
printf 'Update available! 0.128.0 -> 0.130.0\n'
printf 'Press enter to continue\n'
IFS= read -r choice
if [ "$choice" != "2" ]; then
  printf 'unexpected choice: %s\n' "$choice"
  exit 2
fi
printf 'model: test\n'
printf 'Tip: fake\n'
IFS= read -r command
if [ "$command" != "/status" ]; then
  printf 'unexpected command: %s\n' "$command"
  exit 3
fi
printf '5h limit:             [####################] 98%% left (resets 18:38)\n'
printf 'Weekly limit:         [####----------------] 22%% left (resets 10:20 on 8 May)\n'
IFS= read -r exit_command
exit 0
`
	if err := os.WriteFile(fakeCodex, []byte(script), 0o755); err != nil {
		t.Fatalf("write fake codex: %v", err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	checker := NewCodexChecker(fakeCodex)
	status, err := checker.Check(ctx)
	if err != nil {
		t.Fatalf("Check failed: %v", err)
	}
	if status.DailyLimit != "98%" {
		t.Fatalf("DailyLimit: got %q want %q", status.DailyLimit, "98%")
	}
	if status.WeeklyLimit != "22%" {
		t.Fatalf("WeeklyLimit: got %q want %q", status.WeeklyLimit, "22%")
	}
	if status.WeeklyResetTime != "10:20 on 8 May" {
		t.Fatalf("WeeklyResetTime: got %q want %q", status.WeeklyResetTime, "10:20 on 8 May")
	}
}

func TestCodexChecker(t *testing.T) {
	t.Skip("Skipping interactive TUI test by default")

	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
	defer cancel()

	checker := NewCodexChecker("codex")
	status, err := checker.Check(ctx)
	if err != nil {
		t.Fatalf("Failed to check codex status: %v", err)
	}

	fmt.Printf("Raw Output:\n%s\n", status.RawOutput)
	fmt.Printf("Daily Limit: %s\n", status.DailyLimit)
	fmt.Printf("Daily Reset Time: %s\n", status.DailyResetTime)
	fmt.Printf("Weekly Limit: %s\n", status.WeeklyLimit)
	fmt.Printf("Weekly Reset Time: %s\n", status.WeeklyResetTime)
}
