// Archive Films: a complete example MediaProxy source plugin.
//
// It lists public-domain feature films from the Internet Archive
// (archive.org), searches them, and resolves each one to a playable MP4.
// Everything here is the real plugin contract: build it inside the
// mediaproxy2 repository and drop the binary into the plugin folder.
//
//	mkdir -p cmd/plugins/archivefilms && cp main.go cmd/plugins/archivefilms/
//	go build -o bin/plugins/archivefilms ./cmd/plugins/archivefilms
//	./bin/plugintest -plugin bin/plugins/archivefilms validate
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"sync"

	pluginv1 "mediaproxy2/pkg/pluginv1"
	"mediaproxy2/pkg/sdk"
)

const (
	searchURL = "https://archive.org/advancedsearch.php"
	pageSize  = 50
)

// ArchiveFilms implements sdk.Provider.
type ArchiveFilms struct {
	mu         sync.Mutex
	host       *sdk.Host
	collection string
}

// Manifest describes the plugin to the host: identity, what it can do,
// which hosts it may reach, and the settings form shown in the web admin.
func (a *ArchiveFilms) Manifest() *pluginv1.Manifest {
	return &pluginv1.Manifest{
		Id:          "archivefilms",
		Name:        "Archive Films",
		Version:     "1.0.0",
		Description: "Public-domain feature films from the Internet Archive.",
		Homepage:    "https://archive.org/details/feature_films",
		Capabilities: &pluginv1.Capabilities{
			Catalog: true, // ListCategories + ListItems
			Search:  true, // Search
			Details: true, // GetDetails
		},
		Constraints: &pluginv1.Constraints{
			CompleteCatalog: false, // we page through a slice, not everything
		},
		// The host only lets the plugin fetch these hostnames.
		Permissions: &pluginv1.Permissions{Net: []string{"archive.org", "*.archive.org"}},
		Countries:   []string{"global"},
		Languages:   []string{"en"},
		ConfigSchema: []*pluginv1.ConfigField{{
			Key:     "collection",
			Label:   "Collection",
			Type:    pluginv1.ConfigField_TEXT,
			Default: "feature_films",
			Help:    "Which archive.org collection to list, for example feature_films or silent_films.",
		}},
	}
}

// Configure receives the operator's settings and the host services.
// All HTTP must go through host.HTTP so it leaves via the operator's exit.
func (a *ArchiveFilms) Configure(_ context.Context, values map[string]string, host *sdk.Host) error {
	a.mu.Lock()
	defer a.mu.Unlock()
	a.host = host
	a.collection = strings.TrimSpace(values["collection"])
	if a.collection == "" {
		a.collection = "feature_films"
	}
	return nil
}

// TestConnection drives the Test button in the web admin.
func (a *ArchiveFilms) TestConnection(ctx context.Context) error {
	_, err := a.search(ctx, a.query(""), 1, 1)
	return err
}

// ListCategories returns the rows this source offers.
func (a *ArchiveFilms) ListCategories(context.Context) ([]*pluginv1.Category, error) {
	return []*pluginv1.Category{
		{Key: "popular", Name: "Most watched", Sort: 0, Section: sdk.SectionMovies},
		{Key: "recent", Name: "Recently added", Sort: 1, Section: sdk.SectionMovies},
	}, nil
}

// ListItems pages through one category. The cursor is ours to define:
// here it is the next archive.org page number.
func (a *ArchiveFilms) ListItems(ctx context.Context, categoryKey, cursor string, limit int) (*pluginv1.ItemPage, error) {
	page, _ := strconv.Atoi(cursor)
	if page < 1 {
		page = 1
	}
	if limit <= 0 || limit > pageSize {
		limit = pageSize
	}
	sort := "downloads desc"
	if categoryKey == "recent" {
		sort = "addeddate desc"
	}
	docs, err := a.searchSorted(ctx, a.query(""), sort, page, limit)
	if err != nil {
		return nil, err
	}
	out := &pluginv1.ItemPage{}
	for _, d := range docs {
		out.Items = append(out.Items, d.item(categoryKey))
	}
	if len(docs) == limit && page < 4 { // keep the example catalogue small
		out.NextCursor = strconv.Itoa(page + 1)
	}
	return out, nil
}

// GetDetails returns one title. Films have no episodes, so Episodes stays empty.
func (a *ArchiveFilms) GetDetails(ctx context.Context, extID string) (*pluginv1.Details, error) {
	docs, err := a.search(ctx, "identifier:"+quote(extID), 1, 1)
	if err != nil {
		return nil, err
	}
	if len(docs) == 0 {
		return nil, fmt.Errorf("%s: not found", extID)
	}
	return &pluginv1.Details{Item: docs[0].item("")}, nil
}

// Search answers the app's search box live.
func (a *ArchiveFilms) Search(ctx context.Context, query string, limit int) (*pluginv1.ItemPage, error) {
	if limit <= 0 || limit > pageSize {
		limit = pageSize
	}
	docs, err := a.search(ctx, a.query(query), 1, limit)
	if err != nil {
		return nil, err
	}
	out := &pluginv1.ItemPage{}
	for _, d := range docs {
		out.Items = append(out.Items, d.item(""))
	}
	return out, nil
}

// ResolvePlayback turns an item into something playable: here the best
// MP4 file of the archive.org item. The host proxies it to every app.
func (a *ArchiveFilms) ResolvePlayback(ctx context.Context, extID string, maxHeight int) (*pluginv1.Playback, error) {
	var meta struct {
		Files []struct {
			Name   string `json:"name"`
			Format string `json:"format"`
			Height string `json:"height"`
		} `json:"files"`
	}
	if err := a.getJSON(ctx, "https://archive.org/metadata/"+url.PathEscape(extID), &meta); err != nil {
		return nil, err
	}
	best, bestHeight := "", 0
	for _, f := range meta.Files {
		if !strings.HasSuffix(strings.ToLower(f.Name), ".mp4") {
			continue
		}
		h, _ := strconv.Atoi(f.Height)
		if maxHeight > 0 && h > maxHeight {
			continue
		}
		if best == "" || h > bestHeight {
			best, bestHeight = f.Name, h
		}
	}
	if best == "" {
		// A described outcome, not an error: the apps show the reason.
		return &pluginv1.Playback{UnavailableReason: "This item has no MP4 file."}, nil
	}
	return &pluginv1.Playback{
		Locator: &pluginv1.Locator{
			Scheme: pluginv1.Scheme_MP4,
			Url:    "https://archive.org/download/" + url.PathEscape(extID) + "/" + url.PathEscape(best),
		},
		Height: uint32(bestHeight),
		Lang:   "en",
	}, nil
}

// --- archive.org helpers -------------------------------------------------

type doc struct {
	Identifier  string `json:"identifier"`
	Title       string `json:"title"`
	Description any    `json:"description"` // a string or a list of strings
	Year        any    `json:"year"`
}

func (d doc) item(category string) *pluginv1.Item {
	year, _ := strconv.Atoi(fmt.Sprint(d.Year))
	return &pluginv1.Item{
		ExtId:       d.Identifier,
		Type:        pluginv1.ItemType_MOVIE,
		Title:       d.Title,
		Description: text(d.Description),
		Year:        int32(year),
		CategoryKey: category,
		Image:       &pluginv1.ImageRef{Url: "https://archive.org/services/img/" + d.Identifier},
		WebUrl:      "https://archive.org/details/" + d.Identifier,
		Lang:        "en",
	}
}

func (a *ArchiveFilms) query(words string) string {
	a.mu.Lock()
	q := "collection:" + quote(a.collection) + " AND mediatype:movies"
	a.mu.Unlock()
	if words = strings.TrimSpace(words); words != "" {
		q += " AND title:(" + words + ")"
	}
	return q
}

func (a *ArchiveFilms) search(ctx context.Context, q string, page, rows int) ([]doc, error) {
	return a.searchSorted(ctx, q, "downloads desc", page, rows)
}

func (a *ArchiveFilms) searchSorted(ctx context.Context, q, sort string, page, rows int) ([]doc, error) {
	v := url.Values{}
	v.Set("q", q)
	for _, f := range []string{"identifier", "title", "description", "year"} {
		v.Add("fl[]", f)
	}
	v.Set("sort[]", sort)
	v.Set("rows", strconv.Itoa(rows))
	v.Set("page", strconv.Itoa(page))
	v.Set("output", "json")
	var res struct {
		Response struct {
			Docs []doc `json:"docs"`
		} `json:"response"`
	}
	if err := a.getJSON(ctx, searchURL+"?"+v.Encode(), &res); err != nil {
		return nil, err
	}
	return res.Response.Docs, nil
}

func (a *ArchiveFilms) getJSON(ctx context.Context, u string, into any) error {
	a.mu.Lock()
	host := a.host
	a.mu.Unlock()
	if host == nil {
		return errors.New("not configured")
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
	if err != nil {
		return err
	}
	resp, err := host.HTTP.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("archive.org answered %s", resp.Status)
	}
	return json.NewDecoder(resp.Body).Decode(into)
}

func quote(s string) string { return `"` + strings.ReplaceAll(s, `"`, ``) + `"` }

func text(v any) string {
	switch t := v.(type) {
	case string:
		return t
	case []any:
		if len(t) > 0 {
			return fmt.Sprint(t[0])
		}
	}
	return ""
}

func main() { sdk.Serve(&ArchiveFilms{}) }
