package edge

import (
	"bufio"
	"context"
	"encoding/binary"
	"encoding/hex"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"net"
	_ "net/http/pprof"
	"os"
	"os/signal"
	"proxy-server/edge/core"
	"proxy-server/edge/env"
	"proxy-server/edge/report"
	"proxy-server/utils"
	"time"
)

func Start() error {
	var ctx, cancel = signal.NotifyContext(context.Background(), os.Interrupt, os.Kill)
	defer cancel()

	// 初始化环境变量
	slog.Debug("初始化环境变量...")
	err := env.Init()
	if err != nil {
		return fmt.Errorf("初始化环境变量失败: %w", err)
	}

	// 注册节点
	slog.Debug("注册节点...")
	id, host, err := report.Online()
	if err != nil {
		return fmt.Errorf("注册节点失败: %w", err)
	}

	// 连接到网关
	var errCh = make(chan error)
	go func() {
		err = ctrl(ctx, id, host)
		if err == nil {
			errCh <- err
		}
	}()

	// 等待退出
	select {
	case <-ctx.Done():
	case err := <-errCh:
		if err != nil {
			slog.Error("控制通道发生错误", "err", err)
		}
	}

	return ctx.Err()
}

func ctrl(ctx context.Context, id int32, host string) error {
	ctrlAddr := net.JoinHostPort(host, fmt.Sprintf("%d", core.FwdCtrlPort))
	dataAddr := net.JoinHostPort(host, fmt.Sprintf("%d", core.FwdDataPort))

	slog.Info("建立控制通道", "addr", ctrlAddr)
	conn, err := net.Dial("tcp", ctrlAddr)
	if err != nil {
		return errors.New("连接失败")
	}
	defer utils.Close(conn)
	var reader = bufio.NewReader(conn)

	// 发送开启连接
	err = sendOpen(conn, id)
	if err != nil {
		return fmt.Errorf("发送节点信息失败: %w", err)
	}

	// 异步定时发送心跳
	var writeErr = make(chan error)
	go func() {
		ticker := time.Tick(time.Duration(core.HeartbeatInterval) * time.Second)
		for {
			select {
			case <-ctx.Done():
				writeErr <- nil
				return
			case _ = <-ticker:
				err := sendPing(conn)
				if err != nil {
					writeErr <- fmt.Errorf("发送心跳失败: %w", err)
					return
				}
			}
		}
	}()

	// 异步读取节点命令
	var readErr = make(chan error)
	go func() {
		for {
			// 读取命令
			cmd, err := reader.ReadByte()
			if _, err := utils.WarpConnErr(err); err != nil {
				readErr <- err
				return
			}
			switch cmd {

			// pong 命令，忽略
			case 1:

			// 代理命令
			case 5:
				err := onConn(reader, dataAddr)
				if err != nil {
					readErr <- fmt.Errorf("处理代理命令失败: %w", err)
					return
				}
			}
		}
	}()

	// 等待建立数据通道
	select {
	case <-ctx.Done():
	case err = <-readErr:
	}

	// 发送关闭连接
	slog.Debug("发送关闭连接")
	err = sendClose(conn)
	if err != nil {
		return fmt.Errorf("发送关闭连接失败: %w", err)
	}

	return nil
}

func data(proxy string, destination string, tag [16]byte) error {
	var tagStr = hex.EncodeToString(tag[:])
	slog.Debug("建立数据通道", "tag", tagStr, "addr", destination)

	// 向目标地址建立连接
	var result = 1
	var dstErr error
	dst, err := net.Dial("tcp", destination)
	if err != nil {
		dstErr = ErrDstConnFailed
		result = 0
	}

	// 向服务端建立连接
	src, err := net.Dial("tcp", proxy)
	if err != nil {
		return errors.New("连接服务端失败")
	}

	// 发送连接状态
	var buf = make([]byte, 17)
	copy(buf[0:16], tag[:])
	buf[16] = byte(result)
	_, err = src.Write(buf)
	if err != nil {
		return errors.New("发送连接状态失败")
	}

	if result == 0 {
		return dstErr
	}

	var waitSrc = make(chan struct{}, 1)
	go func() {
		defer utils.Close(dst)
		_, err := io.Copy(dst, src)
		if ok, err := utils.WarpConnErr(err); !ok {
			slog.Error("读取网关数据失败", "tag", tagStr, "err", err)
		}
		waitSrc <- struct{}{}
	}()

	var waitDst = make(chan struct{}, 1)
	go func() {
		defer utils.Close(src)
		_, err := io.Copy(src, dst)
		if ok, err := utils.WarpConnErr(err); !ok {
			slog.Error("读取目标数据失败", "err", err)
		}
		waitDst <- struct{}{}
	}()

	// 等待连接全部安全关闭或超时
	<-waitSrc
	<-waitDst

	return nil
}

func sendOpen(writer io.Writer, id int32) error {

	// 发送打开连接
	var buf = make([]byte, 5)
	buf[0] = 3
	binary.BigEndian.PutUint32(buf[1:], uint32(id))

	_, err := writer.Write(buf)
	if err != nil {
		return fmt.Errorf("发送打开连接失败: %w", err)
	}

	return nil
}

func sendClose(writer io.Writer) error {
	// 发送关闭连接
	_, err := writer.Write([]byte{4})
	if err != nil {
		return err
	}

	return nil
}

func sendPing(writer io.Writer) error {
	_, err := writer.Write([]byte{2})
	if err != nil {
		return err
	}

	return nil
}

func onConn(reader io.Reader, dataAddr string) (err error) {

	// 读取连接命令
	var buf = make([]byte, 16+2)
	_, err = io.ReadFull(reader, buf)
	if err != nil {
		return err
	}

	var tag = [16]byte(buf[0:16])

	var addrLen = binary.BigEndian.Uint16(buf[16:18])
	var addrBuf = make([]byte, addrLen)
	_, err = io.ReadFull(reader, addrBuf)
	if err != nil {
		return err
	}
	var addr = string(addrBuf)

	// 异步建立数据通道
	go func() {
		err := data(dataAddr, addr, tag)
		switch {
		case errors.Is(err, ErrDstConnFailed):
			slog.Debug("目标地址连接失败", "tag", hex.EncodeToString(tag[:]), "addr", addr)
		case err != nil:
			slog.Error("建立数据通道失败", "err", err)
		}
	}()

	return nil
}

type ConnCmd struct {
	Tag  [16]byte
	Addr string
}

type Err string

func (e Err) Error() string {
	return string(e)
}

const (
	ErrDstConnFailed = Err("目标地址连接失败")
)
