// Copyright (c) 2026 Alibaba Group and its affiliates

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package sdk

import (
	"bufio"
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"testing"
	"time"
)

func TestReportWriter_AppendsJSONL(t *testing.T) {
	dir := t.TempDir()
	w := newReportWriter(dir)
	defer w.Close()

	rec1 := &TransparencyAuditRecord{RequestID: "req-1", Timestamp: time.Now(), Model: "m"}
	rec2 := &TransparencyAuditRecord{RequestID: "req-2", Timestamp: time.Now(), Model: "m"}
	if err := w.Write(rec1); err != nil {
		t.Fatalf("write rec1: %v", err)
	}
	if err := w.Write(rec2); err != nil {
		t.Fatalf("write rec2: %v", err)
	}

	dateStr := time.Now().Format("2006-01-02")
	expected := filepath.Join(dir, fmt.Sprintf("reports-%s-%d.jsonl", dateStr, os.Getpid()))
	f, err := os.Open(expected)
	if err != nil {
		t.Fatalf("open report file: %v", err)
	}
	defer f.Close()

	scanner := bufio.NewScanner(f)
	var ids []string
	for scanner.Scan() {
		var rec TransparencyAuditRecord
		if err := json.Unmarshal(scanner.Bytes(), &rec); err != nil {
			t.Fatalf("invalid jsonl line %q: %v", scanner.Text(), err)
		}
		ids = append(ids, rec.RequestID)
	}
	if err := scanner.Err(); err != nil {
		t.Fatalf("scan: %v", err)
	}
	if len(ids) != 2 || ids[0] != "req-1" || ids[1] != "req-2" {
		t.Fatalf("unexpected ids: %v", ids)
	}
}

func TestReportWriter_DateRotation(t *testing.T) {
	dir := t.TempDir()
	w := newReportWriter(dir)
	defer w.Close()

	if err := w.Write(&TransparencyAuditRecord{RequestID: "req-today"}); err != nil {
		t.Fatalf("write today: %v", err)
	}
	oldFile := w.currentFile

	// Force rotation by setting an out-of-date sentinel.
	w.mu.Lock()
	w.currentDate = "1970-01-01"
	w.mu.Unlock()

	if err := w.Write(&TransparencyAuditRecord{RequestID: "req-rotated"}); err != nil {
		t.Fatalf("write rotated: %v", err)
	}
	if w.currentFile == oldFile {
		t.Fatalf("expected new file handle after rotation")
	}

	dateStr := time.Now().Format("2006-01-02")
	path := filepath.Join(dir, fmt.Sprintf("reports-%s-%d.jsonl", dateStr, os.Getpid()))
	data, err := os.ReadFile(path)
	if err != nil {
		t.Fatalf("read report: %v", err)
	}
	lines := strings.Split(strings.TrimRight(string(data), "\n"), "\n")
	if len(lines) != 2 {
		t.Fatalf("expected 2 lines after rotation re-open, got %d", len(lines))
	}
}

func TestReportWriter_ConcurrentWrites(t *testing.T) {
	dir := t.TempDir()
	w := newReportWriter(dir)
	defer w.Close()

	const n = 50
	var wg sync.WaitGroup
	wg.Add(n)
	for i := 0; i < n; i++ {
		go func(i int) {
			defer wg.Done()
			_ = w.Write(&TransparencyAuditRecord{RequestID: fmt.Sprintf("req-%d", i)})
		}(i)
	}
	wg.Wait()

	dateStr := time.Now().Format("2006-01-02")
	path := filepath.Join(dir, fmt.Sprintf("reports-%s-%d.jsonl", dateStr, os.Getpid()))
	f, err := os.Open(path)
	if err != nil {
		t.Fatalf("open: %v", err)
	}
	defer f.Close()

	scanner := bufio.NewScanner(f)
	count := 0
	for scanner.Scan() {
		var rec TransparencyAuditRecord
		if err := json.Unmarshal(scanner.Bytes(), &rec); err != nil {
			t.Fatalf("invalid line: %v", err)
		}
		count++
	}
	if count != n {
		t.Fatalf("expected %d lines, got %d", n, count)
	}
}
