package main

import (
	"context"
	"crypto/sha1"
	"encoding/xml"
	"errors"
	"fmt"
	"html"
	"os"
	"path/filepath"
	"strings"
	"syscall"
	"time"
)

type StreamInfo struct {
	Channel   string
	Title     string
	StreamID  string
	StartedAt time.Time
}

type RSS struct {
	XMLName xml.Name   `xml:"rss"`
	Version string     `xml:"version,attr"`
	Channel RSSChannel `xml:"channel"`
}

type RSSChannel struct {
	Title         string    `xml:"title"`
	Link          string    `xml:"link"`
	Description   string    `xml:"description,omitempty"`
	LastBuildDate string    `xml:"lastBuildDate"`
	TTL           int       `xml:"ttl"`
	Items         []RSSItem `xml:"item"`
}

type RSSItem struct {
	Title       string   `xml:"title"`
	Links       []string `xml:"link"`
	Description string   `xml:"description"`
	Guid        string   `xml:"guid"`
	PubDate     string   `xml:"pubDate"`
}

func rssFilePath(channel string, cfg *Config) string {
	return filepath.Join(cfg.DataDir, "feeds", channel+".rss")
}

func lockDataDir(cfg *Config) (*os.File, error) {
	dir := cfg.DataDir
	path := filepath.Join(dir, "tweed.lock")
	f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0644)
	if err != nil {
		return nil, fmt.Errorf("data dir %s: %w", dir, err)
	}
	if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
		f.Close()
		if errors.Is(err, syscall.EWOULDBLOCK) {
			return nil, fmt.Errorf("another tweed instance is using data dir %s", dir)
		}
		return nil, fmt.Errorf("data dir %s: locking %s: %w", dir, path, err)
	}
	if err := f.Truncate(0); err != nil {
		f.Close()
		return nil, fmt.Errorf("data dir %s: %w", dir, err)
	}
	if _, err := fmt.Fprintf(f, "%d\n", os.Getpid()); err != nil {
		f.Close()
		return nil, fmt.Errorf("data dir %s: %w", dir, err)
	}
	return f, nil
}

func getPermanentVODURLs(ctx context.Context, cfg *Config, stream *StreamInfo) []string {
	timestamp := stream.StartedAt.Unix()
	raw := fmt.Sprintf("%s_%s_%d", stream.Channel, stream.StreamID, timestamp)
	h := sha1.Sum([]byte(raw))
	sha20 := fmt.Sprintf("%x", h)[:20]

	path := fmt.Sprintf("%s_%s/chunked/index-dvr.m3u8", sha20, raw)

	return probeCDNs(ctx, cfg.CDNDomains, path, 3)
}

func loadRSS(channel string, cfg *Config) (RSS, error) {
	path := rssFilePath(channel, cfg)
	data, err := os.ReadFile(path)
	if err != nil {
		return RSS{}, err
	}
	var rss RSS
	if err := xml.Unmarshal(data, &rss); err != nil {
		return RSS{}, err
	}
	return rss, nil
}

func saveRSS(channel string, rss RSS, cfg *Config) error {
	out, err := xml.MarshalIndent(rss, "", "  ")
	if err != nil {
		return err
	}
	out = append([]byte(xml.Header), out...)

	path := rssFilePath(channel, cfg)
	dir := filepath.Dir(path)
	if err := os.Mkdir(dir, 0755); err != nil && !errors.Is(err, os.ErrExist) {
		return err
	}
	tmp, err := os.CreateTemp(filepath.Dir(path), "."+channel+".rss.*")
	if err != nil {
		return err
	}
	defer os.Remove(tmp.Name()) // clean up on failure

	if _, err := tmp.Write(out); err != nil {
		tmp.Close()
		return err
	}
	if err := tmp.Sync(); err != nil {
		tmp.Close()
		return err
	}
	if err := tmp.Close(); err != nil {
		return err
	}
	if err := os.Chmod(tmp.Name(), 0644); err != nil {
		return err
	}
	return os.Rename(tmp.Name(), path)
}

func newRSS(cfg *Config, channel string) RSS {
	return RSS{
		Version: "2.0",
		Channel: RSSChannel{
			Title:         channel + "'s Twitch streams",
			Link:          "https://twitch.tv/" + channel, // NOTE: should maybe be tweed link
			Description:   "A feed of " + channel + "'s streams.",
			LastBuildDate: time.Now().Format(time.RFC1123Z), // TODO: what time format to use?
			TTL:           cfg.TTLMinutes,
		},
	}
}

func initEmptyFeeds(cfg *Config) error {
	for _, c := range cfg.Channels {
		if _, err := os.Stat(rssFilePath(c, cfg)); errors.Is(err, os.ErrNotExist) {
			rss := newRSS(cfg, c)
			if err := saveRSS(c, rss, cfg); err != nil {
				return err
			}
		}
	}
	return nil
}

func makeRSSDescription(cdns []string) string {
	var sb strings.Builder
	// TODO: add some message like 'x whent live at y, stream id: z'
	sb.WriteString("<h2>CDN links:</h2>\n")
	sb.WriteString("<ul>\n")
	for _, u := range cdns {
		escaped := html.EscapeString(u)
		sb.WriteString(fmt.Sprintf(
			`  <li><a href="%s" target="_blank" rel="noopener noreferrer">%s</a></li>`+"\n",
			escaped, escaped,
		))
	}
	sb.WriteString("</ul>\n")

	return sb.String()
}

func updateRSSWithNewStream(ctx context.Context, cfg *Config, stream *StreamInfo) error {
	rss, err := loadRSS(stream.Channel, cfg)
	if errors.Is(err, os.ErrNotExist) {
		rss = newRSS(cfg, stream.Channel)
	} else if err != nil {
		return fmt.Errorf("loading feed for %s: %w", stream.Channel, err)
	}
	for _, item := range rss.Channel.Items {
		if item.Guid == stream.StreamID {
			logInfo("stream %s already in feed for %s", stream.StreamID, stream.Channel)
			return nil
		}
	}

	channelUrl := "https://twitch.tv/" + stream.Channel

	links := getPermanentVODURLs(ctx, cfg, stream)
	if ctx.Err() != nil {
		return ctx.Err()
	}
	if len(links) == 0 {
		links = []string{channelUrl}
	}
	pub := stream.StartedAt.Format(time.RFC822Z)

	item := RSSItem{
		Title:       stream.Title,
		Links:       links,
		Description: makeRSSDescription(links),
		Guid:        stream.StreamID,
		PubDate:     pub,
	}

	rss.Channel.Items = append([]RSSItem{item}, rss.Channel.Items...)
	rss.Channel.LastBuildDate = time.Now().Format(time.RFC1123Z)
	rss.Channel.TTL = cfg.TTLMinutes

	logInfo("storing stream '%s' from %s, %d cdn links", stream.Title, stream.Channel, len(links))

	return saveRSS(stream.Channel, rss, cfg)
}
