package main

import (
	"context"
	_ "embed"
	"github.com/chromedp/chromedp"
	"github.com/gorilla/websocket"
	"github.com/ssgo/log"
	"github.com/ssgo/s"
	"github.com/ssgo/u"
	"time"
)

//go:embed client.txt
var clientData string

var conn *websocket.Conn

type Message struct {
	Type      string
	Url       string
	ImageData string
	Text      string
}

func main() {
	//u.WriteFile("client.txt", u.Json(u.LoadFileToB64("web")))
	u.LoadFilesToMemoryFromJson(clientData)
	s.Config.Listen = "9000"
	s.Static("/", "web/")
	s.RegisterSimpleWebsocket(0, "/socket", func(connect *websocket.Conn) {
		log.DefaultLogger.Info("Socket connected")
		conn = connect
		for {
			data := &Message{}
			err := conn.ReadJSON(data)
			if err != nil {
				log.DefaultLogger.Error("Read WS error", "err", err.Error())
				return
			}
			go onMessage(data)
		}
	}, "")
	as := s.AsyncStart()

	// 1. 创建选项（禁用Headless模式以显示窗口）
	opts := append(chromedp.DefaultExecAllocatorOptions[:],
		chromedp.Flag("headless", false),   // 显示浏览器窗口
		chromedp.Flag("disable-gpu", true), // 某些环境需要禁用GPU
		chromedp.Flag("no-sandbox", true),  // 非沙盒模式
	)

	// 2. 初始化浏览器上下文
	ctx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
	defer cancel()
	ctx, cancel = chromedp.NewContext(ctx)
	defer cancel()

	// 3. 导航到网页并保持窗口打开（通过超时控制）
	url := "http://localhost:9000"
	if err := chromedp.Run(ctx,
		chromedp.Navigate(url),
		chromedp.Sleep(365*24*time.Hour), // 设置长期等待（避免立即退出）
	); err != nil {
		as.Stop()
	}
}

func onMessage(data *Message) {
	switch data.Type {
	case "checkPhishing":
		checkUrl(data.Url)
	case "checkImage":
		checkImg(data.ImageData)
	case "checkScript":
		checkText(data.Text)

	}
}
