package main

import (
	"fmt"
	"log"
	"net/http"
	"net/url"
	"strings"

	"github.com/PuerkitoBio/goquery"
)

const TORRENTGALAXY_DOMAIN = "torrentgalaxy.to"

type TorrentGalaxy struct{}

func NewTorrentGalaxy() *TorrentGalaxy {
	return &TorrentGalaxy{}
}

func (tg *TorrentGalaxy) Name() string {
	return "torrentgalaxy"
}

func (tg *TorrentGalaxy) getCategoryCode(category string) string {
	switch category {
	case "all":
		return ""
	case "audiobook":
		return "&c13=1"
	case "movie":
		return "&c3=1&c46=1&c45=1&c42=1&c4=1&c1=1"
	case "tv":
		return "&c41=1&c5=1&c11=1&c6=1&c7=1"
	case "games":
		return "&c43=1&c10=1"
	case "software":
		return "&c20=1&c21=1&c18=1"
	case "anime":
		return "&c28=1"
	case "music":
		return "&c28=1&c22=1&c26=1&c23=1&c25=1&c24=1"
	case "xxx":
		safeSearch := true // Replace with actual safe search status
		if safeSearch {
			return "ignore"
		}
		return "&c48=1&c35=1&c47=1&c34=1"
	default:
		return ""
	}
}

func (tg *TorrentGalaxy) Search(query string, category string) ([]TorrentResult, error) {
	categoryCode := tg.getCategoryCode(category)
	if categoryCode == "ignore" {
		return []TorrentResult{}, nil
	}

	searchURL := fmt.Sprintf("https://%s/torrents.php?search=%s%s#results", TORRENTGALAXY_DOMAIN, url.QueryEscape(query), categoryCode)

	// User Agent generation
	userAgent, err := GetUserAgent("files-torrentgalaxy")
	if err != nil {
		fmt.Println("Error:", err)
		return nil, err
	}

	req, err := http.NewRequest("GET", searchURL, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("User-Agent", userAgent)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("error making request to TorrentGalaxy: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
	}

	doc, err := goquery.NewDocumentFromReader(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("error parsing HTML: %w", err)
	}

	var results []TorrentResult
	doc.Find("div.tgxtablerow").Each(func(i int, s *goquery.Selection) {
		titleDiv := s.Find("div#click > div > a.txlight")
		title := strings.TrimSpace(titleDiv.Text())
		magnetLink, exists := s.Find("a[href^='magnet']").Attr("href")

		fmt.Printf("Found title: %s\n", title)            // Debugging statement
		fmt.Printf("Found magnet link: %s\n", magnetLink) // Debugging statement

		if !exists {
			log.Printf("No magnet link found for title: %s", title)
			return
		}

		byteSize := parseSize(s.Find("span.badge-secondary").Text())
		viewCount := parseInt(s.Find("span.badge-warning font[color='orange']").Text())
		seeder := parseInt(s.Find("span[title='Seeders/Leechers'] font[color='green']").Text())
		leecher := parseInt(s.Find("span[title='Seeders/Leechers'] font[color='#ff0000']").Text())

		result := TorrentResult{
			URL:      fmt.Sprintf("https://%s", TORRENTGALAXY_DOMAIN),
			Seeders:  seeder,
			Leechers: leecher,
			Magnet:   applyTrackers(magnetLink),
			Views:    viewCount,
			Size:     formatSize(byteSize),
			Title:    title,
		}
		results = append(results, result)
	})

	return results, nil
}