package app

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	amcsllm "git.warky.dev/wdevs/amcs/llm"
)

func TestServeLLMInstructions(t *testing.T) {
	req := httptest.NewRequest(http.MethodGet, "/llm", nil)
	rec := httptest.NewRecorder()

	serveLLMInstructions(rec, req)

	res := rec.Result()
	defer func() {
		_ = res.Body.Close()
	}()

	if res.StatusCode != http.StatusOK {
		t.Fatalf("status = %d, want %d", res.StatusCode, http.StatusOK)
	}
	if got := res.Header.Get("Content-Type"); got != "text/markdown; charset=utf-8" {
		t.Fatalf("content-type = %q, want %q", got, "text/markdown; charset=utf-8")
	}
	if body := rec.Body.String(); body != string(amcsllm.MemoryInstructions) {
		t.Fatalf("body = %q, want embedded instructions", body)
	}
}

func TestServeRobotsTXT(t *testing.T) {
	req := httptest.NewRequest(http.MethodGet, "/robots.txt", nil)
	req.Host = "amcs.example.com"
	req.Header.Set("X-Forwarded-Proto", "https")
	rec := httptest.NewRecorder()

	serveRobotsTXT(rec, req)

	res := rec.Result()
	defer func() {
		_ = res.Body.Close()
	}()

	if res.StatusCode != http.StatusOK {
		t.Fatalf("status = %d, want %d", res.StatusCode, http.StatusOK)
	}
	if got := res.Header.Get("Content-Type"); got != "text/plain; charset=utf-8" {
		t.Fatalf("content-type = %q, want %q", got, "text/plain; charset=utf-8")
	}
	body := rec.Body.String()
	if !strings.Contains(body, "LLM: https://amcs.example.com/llm") {
		t.Fatalf("body = %q, want LLM link", body)
	}
	if !strings.Contains(body, "LLMS: https://amcs.example.com/llms.txt") {
		t.Fatalf("body = %q, want LLMS link", body)
	}
}

func TestServeLLMSTXT(t *testing.T) {
	req := httptest.NewRequest(http.MethodGet, "/llms.txt", nil)
	req.Host = "amcs.example.com"
	req.Header.Set("X-Forwarded-Proto", "https")
	rec := httptest.NewRecorder()

	serveLLMSTXT(rec, req)

	res := rec.Result()
	defer func() {
		_ = res.Body.Close()
	}()

	if res.StatusCode != http.StatusOK {
		t.Fatalf("status = %d, want %d", res.StatusCode, http.StatusOK)
	}
	if got := res.Header.Get("Content-Type"); got != "text/plain; charset=utf-8" {
		t.Fatalf("content-type = %q, want %q", got, "text/plain; charset=utf-8")
	}
	body := rec.Body.String()
	if !strings.Contains(body, "https://amcs.example.com/llm") {
		t.Fatalf("body = %q, want /llm link", body)
	}
	if !strings.Contains(body, "https://amcs.example.com/.well-known/oauth-authorization-server") {
		t.Fatalf("body = %q, want oauth discovery link", body)
	}
}

func TestServeLLMSTXTWellKnownPath(t *testing.T) {
	req := httptest.NewRequest(http.MethodGet, "/.well-known/llms.txt", nil)
	rec := httptest.NewRecorder()

	serveLLMSTXT(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
	}
}
