package ilink

import (
	"bytes"
	"context"
	"crypto/aes"
	"crypto/md5"
	"crypto/rand"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"math"
	"net/http"
	"strconv"
	"strings"
	"time"
)

const (
	DefaultBaseURL = "https://ilinkai.weixin.qq.com"
	CDNBaseURL     = "https://novac2c.cdn.weixin.qq.com/c2c"
	channelVersion = "1.0.0"
)

type Credentials struct {
	Token      string    `json:"token"`
	BaseURL    string    `json:"baseUrl"`
	AccountID  string    `json:"accountId"`
	UserID     string    `json:"userId"`
	SavedAt    time.Time `json:"savedAt"`
	UpdatesBuf string    `json:"get_updates_buf"`
}

type QRResult struct {
	QRCode string `json:"qrcode"`
	QRImg  string `json:"qrcode_img_content"`
	Ret    int    `json:"ret"`
}

type QRStatus struct {
	Status       string `json:"status"`
	BotToken     string `json:"bot_token"`
	BotID        string `json:"ilink_bot_id"`
	UserID       string `json:"ilink_user_id"`
	BaseURL      string `json:"baseurl"`
	RedirectHost string `json:"redirect_host"`
	VerifyCode   string `json:"verify_code"`
}

type TextItem struct {
	Text string `json:"text"`
}

type CDNMedia struct {
	EncryptQueryParam string `json:"encrypt_query_param"`
	AESKey            string `json:"aes_key"`
	EncryptType       int    `json:"encrypt_type"`
}

type ImageItem struct {
	Media CDNMedia `json:"media"`
	Size  int64    `json:"mid_size"`
}

type FileItem struct {
	Media    CDNMedia `json:"media"`
	FileName string   `json:"file_name"`
	Len      int64    `json:"len"`
}

type VoiceItem struct {
	Media      CDNMedia `json:"media"`
	EncodeType int      `json:"encode_type"`
	PlayTime   int64    `json:"playtime"`
	Text       string   `json:"text"`
}

type MessageItem struct {
	Type      int        `json:"type"`
	TextItem  *TextItem  `json:"text_item,omitempty"`
	ImageItem *ImageItem `json:"image_item,omitempty"`
	FileItem  *FileItem  `json:"file_item,omitempty"`
	VoiceItem *VoiceItem `json:"voice_item,omitempty"`
}

type Incoming struct {
	Seq          int64          `json:"seq"`
	MessageID    int64          `json:"message_id"`
	FromUserID   string         `json:"from_user_id"`
	ToUserID     string         `json:"to_user_id"`
	ClientID     string         `json:"client_id"`
	CreateTimeMs int64          `json:"create_time_ms"`
	SessionID    string         `json:"session_id"`
	MessageType  int            `json:"message_type"`
	MessageState int            `json:"message_state"`
	ContextToken string         `json:"context_token"`
	Items        []MessageItem  `json:"item_list"`
}

type UpdatesResult struct {
	Ret       int        `json:"ret"`
	Errcode   int        `json:"errcode"`
	Msgs      []Incoming `json:"msgs"`
	UpdatesBuf string    `json:"get_updates_buf"`
	TimeoutMs int64      `json:"longpolling_timeout_ms"`
}

type Client struct {
	HTTP       *http.Client
	Token      string
	Base       string
	QrBase     string
	QrRedirect string
	UserID     string
}

func NewClient(creds *Credentials) *Client {
	base := creds.BaseURL
	if base == "" {
		base = DefaultBaseURL
	}
	return &Client{
		HTTP:   &http.Client{Timeout: 60 * time.Second},
		Token:  creds.Token,
		Base:   base,
		QrBase: DefaultBaseURL,
		UserID: creds.UserID,
	}
}

func (c *Client) post(ctx context.Context, path string, body interface{}) (*http.Response, error) {
	var buf bytes.Buffer
	if err := json.NewEncoder(&buf).Encode(body); err != nil {
		return nil, err
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.Base+path, &buf)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("AuthorizationType", "ilink_bot_token")
	req.Header.Set("Authorization", "Bearer "+c.Token)
	req.Header.Set("X-WECHAT-UIN", randomUIN())
	return c.HTTP.Do(req)
}

func (c *Client) get(ctx context.Context, url string) (*http.Response, error) {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("iLink-App-ClientVersion", "1")
	req.Header.Set("SKRouteTag", "1001")
	return c.HTTP.Do(req)
}

func GetQRCode(ctx context.Context) (*QRResult, error) {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet,
		DefaultBaseURL+"/ilink/bot/get_bot_qrcode?bot_type=3", nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("SKRouteTag", "1001")
	resp, err := (&http.Client{Timeout: 20 * time.Second}).Do(req)
	if err != nil {
		return nil, fmt.Errorf("get qrcode: %w", err)
	}
	defer resp.Body.Close()
	var r QRResult
	if err := json.NewDecoder(resp.Body).Decode(&r); err != nil {
		return nil, err
	}
	return &r, nil
}

func (c *Client) PollQRStatus(ctx context.Context, qrcode string) (*QRStatus, error) {
	url := c.QrBase + "/ilink/bot/get_qrcode_status?qrcode=" + qrcode
	if c.QrRedirect != "" {
		url = c.QrRedirect + "/ilink/bot/get_qrcode_status?qrcode=" + qrcode
	}
	resp, err := c.get(ctx, url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	var s QRStatus
	if err := json.NewDecoder(resp.Body).Decode(&s); err != nil {
		return nil, err
	}
	if s.RedirectHost != "" {
		c.QrRedirect = "https://" + s.RedirectHost
	}
	return &s, nil
}

// PollQRStatusWithCode polls with an optional verify code (need_verifycode flow).
func (c *Client) PollQRStatusWithCode(ctx context.Context, qrcode, code string) (*QRStatus, error) {
	url := c.QrBase + "/ilink/bot/get_qrcode_status?qrcode=" + qrcode
	if c.QrRedirect != "" {
		url = c.QrRedirect + "/ilink/bot/get_qrcode_status?qrcode=" + qrcode
	}
	if code != "" {
		url += "&verify_code=" + code
	}
	resp, err := c.get(ctx, url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	var s QRStatus
	if err := json.NewDecoder(resp.Body).Decode(&s); err != nil {
		return nil, err
	}
	if s.RedirectHost != "" {
		c.QrRedirect = "https://" + s.RedirectHost
	}
	return &s, nil
}

func (c *Client) GetUpdates(ctx context.Context, buf string, timeoutMs int64) (*UpdatesResult, error) {
	if timeoutMs <= 0 {
		timeoutMs = 35000
	}
	body := map[string]interface{}{
		"get_updates_buf": buf,
		"base_info":       map[string]string{"channel_version": channelVersion},
	}
	resp, err := c.post(ctx, "/ilink/bot/getupdates", body)
	if err != nil {
		if resp != nil {
			resp.Body.Close()
		}
		return nil, err
	}
	defer resp.Body.Close()
	data, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	var u UpdatesResult
	if err := json.Unmarshal(data, &u); err != nil {
		return nil, fmt.Errorf("parse updates: %w: %s", err, string(data))
	}
	return &u, nil
}

func (c *Client) SendText(ctx context.Context, toUser, text, contextToken string) error {
	msg := map[string]interface{}{
		"from_user_id":  "",
		"to_user_id":    toUser,
		"client_id":     newClientID(),
		"message_type":  2,
		"message_state": 2,
		"context_token": contextToken,
		"item_list": []map[string]interface{}{
			{"type": 1, "text_item": map[string]string{"text": text}},
		},
	}
	body := map[string]interface{}{
		"msg":       msg,
		"base_info": map[string]string{"channel_version": channelVersion},
	}
	resp, err := c.post(ctx, "/ilink/bot/sendmessage", body)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("sendmessage status %d", resp.StatusCode)
	}
	return nil
}

func (c *Client) SendMedia(ctx context.Context, toUser, fileName string, data []byte, contextToken string) error {
	encKey := make([]byte, 16)
	if _, err := rand.Read(encKey); err != nil {
		return err
	}
	ciphertext := aesECBEncrypt(data, encKey)

	filekey := randomHex(16)
	rawsize := int64(len(data))
	filesize := int64(math.Ceil(float64(rawsize+1)/16.0) * 16)
	rawmd5 := md5.Sum(data)

	upReq := map[string]interface{}{
		"filekey":       filekey,
		"media_type":    3,
		"to_user_id":    toUser,
		"rawsize":       rawsize,
		"rawfilemd5":    hex.EncodeToString(rawmd5[:]),
		"filesize":      filesize,
		"no_need_thumb": true,
		"aeskey":        hex.EncodeToString(encKey),
		"base_info":     map[string]string{"channel_version": channelVersion},
	}
	upResp, err := c.post(ctx, "/ilink/bot/getuploadurl", upReq)
	if err != nil {
		return err
	}
	var up struct {
		UploadParam string `json:"upload_param"`
	}
	if err := json.NewDecoder(upResp.Body).Decode(&up); err != nil {
		upResp.Body.Close()
		return err
	}
	upResp.Body.Close()
	if up.UploadParam == "" {
		return fmt.Errorf("getuploadurl returned empty upload_param")
	}

	uploadURL := CDNBaseURL + "/upload?encrypted_query_param=" +
		urlQueryEscape(up.UploadParam) + "&filekey=" + filekey
	ureq, err := http.NewRequestWithContext(ctx, http.MethodPost, uploadURL, bytes.NewReader(ciphertext))
	if err != nil {
		return err
	}
	ureq.Header.Set("Content-Type", "application/octet-stream")
	uresp, err := c.HTTP.Do(ureq)
	if err != nil {
		return err
	}
	defer uresp.Body.Close()
	if uresp.StatusCode != http.StatusOK {
		return fmt.Errorf("cdn upload status %d", uresp.StatusCode)
	}
	encParam := uresp.Header.Get("x-encrypted-param")

	item := map[string]interface{}{
		"type": 4,
		"file_item": map[string]interface{}{
			"media": map[string]interface{}{
				"encrypt_query_param": encParam,
				"aes_key":             base64.StdEncoding.EncodeToString([]byte(hex.EncodeToString(encKey))),
				"encrypt_type":        1,
			},
			"file_name": fileName,
			"len":       rawsize,
		},
	}
	msg := map[string]interface{}{
		"from_user_id":  "",
		"to_user_id":    toUser,
		"client_id":     newClientID(),
		"message_type":  2,
		"message_state": 2,
		"context_token": contextToken,
		"item_list":     []map[string]interface{}{item},
	}
	body := map[string]interface{}{
		"msg":       msg,
		"base_info": map[string]string{"channel_version": channelVersion},
	}
	sresp, err := c.post(ctx, "/ilink/bot/sendmessage", body)
	if err != nil {
		return err
	}
	defer sresp.Body.Close()
	if sresp.StatusCode != http.StatusOK {
		return fmt.Errorf("sendmessage media status %d", sresp.StatusCode)
	}
	return nil
}

func (c *Client) DownloadMedia(ctx context.Context, media CDNMedia) ([]byte, error) {
	url := CDNBaseURL + "/download?encrypted_query_param=" + urlQueryEscape(media.EncryptQueryParam)
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		return nil, err
	}
	resp, err := c.HTTP.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	ciphertext, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	key, err := decodeAESKey(media.AESKey)
	if err != nil {
		return nil, err
	}
	return aesECBDecrypt(ciphertext, key)
}

func decodeAESKey(encoded string) ([]byte, error) {
	raw, err := base64.StdEncoding.DecodeString(encoded)
	if err != nil {
		return nil, err
	}
	if len(raw) == 16 {
		return raw, nil
	}
	if len(raw) == 32 {
		if d, err := hex.DecodeString(string(raw)); err == nil && len(d) == 16 {
			return d, nil
		}
		return nil, fmt.Errorf("aes_key 32 bytes not hex")
	}
	return nil, fmt.Errorf("unexpected aes_key length %d", len(raw))
}

func aesECBEncrypt(data, key []byte) []byte {
	block, _ := aes.NewCipher(key)
	blockSize := block.BlockSize()
	padded := pkcs7Pad(data, blockSize)
	out := make([]byte, len(padded))
	for i := 0; i < len(padded); i += blockSize {
		block.Encrypt(out[i:], padded[i:])
	}
	return out
}

func aesECBDecrypt(ciphertext, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	if len(ciphertext)%block.BlockSize() != 0 {
		return nil, fmt.Errorf("ciphertext not multiple of block size")
	}
	out := make([]byte, len(ciphertext))
	for i := 0; i < len(ciphertext); i += block.BlockSize() {
		block.Decrypt(out[i:], ciphertext[i:])
	}
	return pkcs7Unpad(out)
}

func pkcs7Pad(data []byte, blockSize int) []byte {
	pad := blockSize - len(data)%blockSize
	return append(data, bytes.Repeat([]byte{byte(pad)}, pad)...)
}

func pkcs7Unpad(data []byte) ([]byte, error) {
	if len(data) == 0 {
		return nil, fmt.Errorf("empty data")
	}
	pad := int(data[len(data)-1])
	if pad == 0 || pad > len(data) {
		return nil, fmt.Errorf("invalid padding")
	}
	return data[:len(data)-pad], nil
}

func randomUIN() string {
	b := make([]byte, 4)
	_, _ = rand.Read(b)
	val := strconv.FormatUint(uint64(bytesToUint32(b)), 10)
	return base64.StdEncoding.EncodeToString([]byte(val))
}

func bytesToUint32(b []byte) uint32 {
	return uint32(b[0])<<24 | uint32(b[1])<<16 | uint32(b[2])<<8 | uint32(b[3])
}

func newClientID() string {
	return "wilink-bridge:" + strconv.FormatInt(time.Now().UnixNano(), 10) + "-" + randomHex(6)
}

func randomHex(n int) string {
	b := make([]byte, n)
	_, _ = rand.Read(b)
	return hex.EncodeToString(b)
}

func urlQueryEscape(s string) string {
	return strings.ReplaceAll(s, "=", "%3D")
}