package mloco

import (
	"context"
	"crypto/rand"
	"crypto/sha512"
	"crypto/tls"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"
	"time"
)

const (
	androidLoginURL      = "https://katalk.kakao.com/android/account/login.json"
	androidPasscodeURL   = "https://katalk.kakao.com/android/account/passcodeLogin/generate"
	androidRegisterURL   = "https://katalk.kakao.com/android/account/passcodeLogin/registerDevice"
	androidOAuthRefreshURL = "https://katalk.kakao.com/android/account/oauth2_token.json"

	osVersion    = "13"
	agent        = "android"
	lang         = "ko"
	prtVersion   = "1"
	mccMNC       = "999"
	deviceName   = "SM-X200"
	modelName    = "SM-X200"
	androidAPILevel = "33"
)

var appVersion = "11.3.0"

type KakaoAuth struct {
	Client     *http.Client
	mail       string
	password   string
	deviceUUID string
	deviceType string
}

type KakaoLoginResponse struct {
	Status       int    `json:"status"`
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	TokenType    string `json:"token_type"`
	UserID       int64  `json:"userId"`
	AccountID    int64  `json:"accountId"`
	UUID         string `json:"uuid"`
	Remaining    int    `json:"remainingSeconds"`
	Message      any    `json:"message"`
}

type authResult struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	UserID       int    `json:"userId"`
	Status       int    `json:"status"`
}

type AuthResult = authResult

type loginError struct {
	Code    string
	Message string
}

func (e *loginError) Error() string { return e.Message }

func NewKakaoAuth(client *http.Client, mail, password string) *KakaoAuth {
	duuid := ""
	if duuid == "" {
		duuid = makeDeviceID()
	}
	if client == nil {
		client = &http.Client{
			Timeout: 30 * time.Second,
			Transport: &http.Transport{
				TLSClientConfig: &tls.Config{
					InsecureSkipVerify: true,
				},
			},
		}
	}
	return &KakaoAuth{
		Client:     client,
		mail:       mail,
		password:   password,
		deviceUUID: duuid,
		deviceType: "tablet",
	}
}

func (a *KakaoAuth) DeviceUUID() string { return a.deviceUUID }

func (a *KakaoAuth) Email() string { return a.mail }

// LoginStatus performs the login and returns the full raw response so the
// caller can branch on the exact status (e.g. passcode-required for a new
// device). A nil error means the request completed at the HTTP/parse level.
func (a *KakaoAuth) LoginStatus(ctx context.Context) (*KakaoLoginResponse, error) {
	return a.attemptLogin(ctx, true)
}

func makeDeviceID() string {
	buf := make([]byte, 16)
	_, _ = rand.Read(buf)
	return hex.EncodeToString(buf)
}

func (a *KakaoAuth) xvc() string {
	raw := "BARD|" + userAgent() + "|DANTE|" + a.mail + "|SIAN"
	h := sha512.Sum512([]byte(raw))
	return hex.EncodeToString(h[:16])
}

func authHeader() string {
	return agent + "/" + appVersion + "/" + lang
}

func userAgent() string {
	return "KT/" + appVersion + " An/" + osVersion + " " + lang
}

func (a *KakaoAuth) defaultHeaders() http.Header {
	h := http.Header{}
	h.Set("Content-Type", "application/x-www-form-urlencoded")
	h.Set("A", authHeader())
	h.Set("X-VC", a.xvc())
	h.Set("User-Agent", userAgent())
	h.Set("Accept", "*/*")
	h.Set("Accept-Language", lang)
	return h
}

func (a *KakaoAuth) defaultForm() url.Values {
	f := url.Values{}
	f.Set("email", a.mail)
	f.Set("password", a.password)
	f.Set("device_name", deviceName)
	f.Set("device_uuid", a.deviceUUID)
	f.Set("model_name", modelName)
	f.Set("device_type", a.deviceType)
	f.Set("os_version", osVersion)
	return f
}

func (a *KakaoAuth) attemptLogin(ctx context.Context, forced bool) (*KakaoLoginResponse, error) {
	form := a.defaultForm()
	form.Set("permanent", "true")
	if forced {
		form.Set("forced", "true")
	}

	req, err := http.NewRequestWithContext(ctx, http.MethodPost, androidLoginURL, strings.NewReader(form.Encode()))
	if err != nil {
		return nil, err
	}
	req.Header = a.defaultHeaders()

	resp, err := a.Client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("login request: %w", err)
	}
	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("login status=%d body=%s", resp.StatusCode, truncate(string(body), 400))
	}

	var result KakaoLoginResponse
	if err := json.Unmarshal(body, &result); err != nil {
		return nil, fmt.Errorf("parse login response: %w", err)
	}
	return &result, nil
}

func (a *KakaoAuth) Login(ctx context.Context) (*authResult, error) {
	result, err := a.attemptLogin(ctx, true)
	if err != nil {
		return nil, err
	}

	switch result.Status {
	case 0:
		return &authResult{
			AccessToken:  result.AccessToken,
			RefreshToken: result.RefreshToken,
			UserID:       int(result.UserID),
			Status:       0,
		}, nil
	case -100:
		return nil, &loginError{Code: "not_authenticated", Message: "account not authenticated"}
	case -101:
		return nil, &loginError{Code: "already_logged_in", Message: "already logged in elsewhere, log out there first"}
	case 12, 30:
		return nil, &loginError{Code: "bad_credentials", Message: "wrong email or password"}
	default:
		return nil, &loginError{Code: fmt.Sprintf("status_%d", result.Status), Message: fmt.Sprintf("login failed status=%d", result.Status)}
	}
}

// RequestPasscode triggers device registration and returns the code shown on
// the user's phone that they must enter.
func (a *KakaoAuth) RequestPasscode(ctx context.Context) (string, error) {
	body := map[string]any{
		"email":     a.mail,
		"password":  a.password,
		"permanent": true,
		"device": map[string]any{
			"name":     deviceName,
			"uuid":     a.deviceUUID,
			"model":    modelName,
			"osVersion": androidAPILevel,
		},
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, androidPasscodeURL, strings.NewReader(mustJSON(body)))
	if err != nil {
		return "", err
	}
	req.Header = a.defaultHeaders()
	req.Header.Set("Content-Type", "application/json; charset=utf-8")

	resp, err := a.Client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	data, _ := io.ReadAll(resp.Body)

	var parsed struct {
		Status     int    `json:"status"`
		Passcode   string `json:"passcode"`
		Remaining  int    `json:"remainingSeconds"`
	}
	if err := json.Unmarshal(data, &parsed); err != nil {
		return "", fmt.Errorf("parse passcode response: %w body=%s", err, truncate(string(data), 300))
	}
	if parsed.Status != 0 {
		return "", fmt.Errorf("passcode request failed status=%d body=%s", parsed.Status, truncate(string(data), 300))
	}
	return parsed.Passcode, nil
}

func (a *KakaoAuth) RegisterDevice(ctx context.Context, passcode string) error {
	ok, err := a.RegisterDeviceResult(ctx, passcode)
	if err != nil {
		return err
	}
	if !ok {
		return fmt.Errorf("device not registered")
	}
	return nil
}

// RegisterDeviceResult attempts to finalize device registration with the
// passcode that was entered on the phone. It returns (true, nil) when
// registration succeeded, (false, nil) when the phone confirmation is still
// pending (device not yet authorised), and (false, err) on hard failures.
func (a *KakaoAuth) RegisterDeviceResult(ctx context.Context, passcode string) (bool, error) {
	body := map[string]any{
		"email":     a.mail,
		"password":  a.password,
		"permanent": true,
		"device": map[string]any{
			"name":      deviceName,
			"uuid":      a.deviceUUID,
			"model":     modelName,
			"osVersion": androidAPILevel,
		},
		"passcode": passcode,
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, androidRegisterURL, strings.NewReader(mustJSON(body)))
	if err != nil {
		return false, err
	}
	req.Header = a.defaultHeaders()
	req.Header.Set("Content-Type", "application/json; charset=utf-8")

	resp, err := a.Client.Do(req)
	if err != nil {
		return false, err
	}
	defer resp.Body.Close()
	data, _ := io.ReadAll(resp.Body)

	var parsed struct {
		Status int `json:"status"`
	}
	if err := json.Unmarshal(data, &parsed); err != nil {
		return false, fmt.Errorf("parse register response: %w body=%s", err, truncate(string(data), 200))
	}
	if parsed.Status == 0 {
		return true, nil
	}
	// -100 (or similar "not yet authorised") means keep waiting.
	return false, nil
}

func (a *KakaoAuth) RefreshToken(ctx context.Context, accessToken, refreshToken string) (*authResult, error) {
	body := map[string]any{
		"access_token":  accessToken,
		"refresh_token": refreshToken,
		"grant_type":    "refresh_token",
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, androidOAuthRefreshURL, strings.NewReader(mustJSON(body)))
	if err != nil {
		return nil, err
	}
	req.Header = a.defaultHeaders()
	req.Header.Set("Content-Type", "application/json; charset=utf-8")
	req.Header.Set("Authorization", accessToken+"-"+a.deviceUUID)

	resp, err := a.Client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	data, _ := io.ReadAll(resp.Body)

	var result authResult
	if err := json.Unmarshal(data, &result); err != nil {
		return nil, fmt.Errorf("parse refresh response: %w", err)
	}
	if result.Status != 0 {
		return nil, fmt.Errorf("refresh failed status=%d", result.Status)
	}
	return &result, nil
}

func mustJSON(v any) string {
	b, _ := json.Marshal(v)
	return string(b)
}

func truncate(s string, n int) string {
	if len(s) <= n {
		return s
	}
	return s[:n]
}
