package server

import (
	"bytes"
	"errors"
	"fmt"
	"html"
	"net/http"
	"os"
	"path/filepath"
	"strings"

	"tinyadventure/internal/model"
)

var errNoRun = errors.New("no finished run with that id")

func (g *game) run() model.Run {
	s := g.snapshot()
	steps := s.Campaign.Main.Steps
	out := model.Run{
		Game: s.Game, Seed: s.Seed, Phase: s.Phase, Mission: s.Campaign.Main.Name, Day: s.Clock.Day,
		Keys: len(s.Party.Keys), Gold: s.Party.Gold, Summary: s.Summary,
	}
	for _, st := range steps {
		if st.Slots.Item != "" {
			out.KeysOf++
		}
	}
	if enc, ok := g.encs[steps[len(steps)-1].POI]; ok && len(enc.Enemies) > 0 {
		out.Boss = enc.Enemies[0].Name
	}
	for _, u := range s.Party.Units {
		out.Party = append(out.Party, model.RunHero{Name: u.Name, Race: u.Race, Class: u.Class, Level: u.Level})
	}
	return out
}

func (s *Server) findRun(id string) (model.Run, error) {
	if !gameID.MatchString(id) {
		return model.Run{}, errNoRun
	}
	var g *game
	for _, st := range s.seats {
		if st.g.state.Game == id {
			g = st.g
		}
	}
	if g == nil {
		loaded, err := s.store.load(id)
		if err != nil {
			return model.Run{}, errNoRun
		}
		g = loaded
	}
	if !g.finished() {
		return model.Run{}, errNoRun
	}
	return g.run(), nil
}

func (s *Server) lookup(r *http.Request) (model.Run, int, error) {
	if !s.limits.allow(clientIP(r), "read") {
		return model.Run{}, http.StatusTooManyRequests, errors.New("slow down")
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	run, err := s.findRun(r.PathValue("id"))
	if err != nil {
		return run, http.StatusNotFound, err
	}
	return run, http.StatusOK, nil
}

func (s *Server) handleRun(w http.ResponseWriter, r *http.Request) {
	run, code, err := s.lookup(r)
	if err != nil {
		fail(w, code, err)
		return
	}
	reply(w, code, run)
}

func headline(run model.Run) (string, string) {
	names := make([]string, len(run.Party))
	for i, h := range run.Party {
		names[i] = h.Name
	}
	who := strings.Join(names[:len(names)-1], ", ") + " and " + names[len(names)-1]
	if run.Phase == "victory" {
		return fmt.Sprintf("Victory on day %d", run.Day), fmt.Sprintf("%s slew %s. %d battles, %d foes, %d keys. Seed %d.", who, run.Boss, run.Summary.Battles, run.Summary.Kills, run.Keys, run.Seed)
	}
	return fmt.Sprintf("Fell on day %d", run.Day), fmt.Sprintf("%s fell on the road to %s. %d battles, %d foes, %d of %d keys. Seed %d.", who, run.Boss, run.Summary.Battles, run.Summary.Kills, run.Keys, run.KeysOf, run.Seed)
}

func (s *Server) handleShare(w http.ResponseWriter, r *http.Request) {
	page, err := os.ReadFile(filepath.Join(s.web, "index.html"))
	if err != nil {
		fail(w, http.StatusInternalServerError, err)
		return
	}
	if run, _, err := s.lookup(r); err == nil {
		title, desc := headline(run)
		scheme := "http"
		if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" {
			scheme = "https"
		}
		img := fmt.Sprintf("%s://%s/r/%s/card.png", scheme, r.Host, run.Game)
		t, d := html.EscapeString(title+" · Tiny Adventure"), html.EscapeString(desc)
		meta := fmt.Sprintf(`<title>%s</title>
<meta name="description" content="%s">
<meta property="og:title" content="%s">
<meta property="og:description" content="%s">
<meta property="og:image" content="%s">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta name="twitter:card" content="summary_large_image">`, t, d, t, d, img)
		if i := bytes.Index(page, []byte("<title>")); i >= 0 {
			if n := bytes.IndexByte(page[i:], '\n'); n >= 0 {
				page = append(page[:i:i], append([]byte(meta), page[i+n:]...)...)
			}
		}
	}
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.Header().Set("Cache-Control", "no-cache")
	w.Write(page)
}

func (s *Server) handleCard(w http.ResponseWriter, r *http.Request) {
	run, code, err := s.lookup(r)
	if err != nil {
		fail(w, code, err)
		return
	}
	cached := ""
	if s.store.dir != "" {
		cached = s.store.path("cards", run.Game+".png")
		if b, err := os.ReadFile(cached); err == nil {
			writePNG(w, b)
			return
		}
	}
	b, err := card(run, r.Host)
	if err != nil {
		fail(w, http.StatusInternalServerError, err)
		return
	}
	if cached != "" {
		os.WriteFile(cached, b, 0o644)
	}
	writePNG(w, b)
}

func writePNG(w http.ResponseWriter, b []byte) {
	w.Header().Set("Content-Type", "image/png")
	w.Header().Set("Cache-Control", "public, max-age=86400")
	w.Write(b)
}
