// Package mytelegram replicates the login + app-creation flow that a browser
// performs on https://my.telegram.org. It is the Go port of the reference
// Python implementation shipped with the project:
//
//  1. POST /auth/send_password  {phone}            -> {"random_hash": ...}
//  2. POST /auth/login           {phone, random_hash, password(=OTP)} -> stel_token cookie
//  3. GET  /apps                                       -> hidden form "hash"
//  4. POST /apps/create          {hash, app_title, app_shortname, app_url, app_platform, app_desc}
//  5. GET  /apps                                       -> <span>api_id</span><span>api_hash</span>
//
// The OTP requested in step 1 is the login code Telegram pushes to the
// account's existing Telegram app, not the 2FA cloud password.
package mytelegram

import (
	"context"
	"crypto/tls"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/url"
	"regexp"
	"strings"
	"time"

	"golang.org/x/net/html"
	"golang.org/x/net/proxy"
)

// Proxy describes how to dial out to my.telegram.org.
type Proxy struct {
	Kind     string // "http" | "https" | "socks5" | "none"
	Host     string
	Port     int
	Username string
	Password string
}

// URL renders the proxy as an opaque URL usable by net/url.Parse.
func (p Proxy) URL() string {
	if p.Kind == "none" || p.Kind == "" || p.Host == "" {
		return ""
	}
	scheme := p.Kind
	if scheme == "https" {
		scheme = "http"
	}
	u := &url.URL{Scheme: scheme, Host: fmt.Sprintf("%s:%d", p.Host, p.Port)}
	if p.Username != "" {
		u.User = url.UserPassword(p.Username, p.Password)
	}
	return u.String()
}

// Options control an individual session.
type Options struct {
	// Timeout for each HTTP request. 0 => 20s.
	Timeout time.Duration
	// UserAgent sent on every request. Empty => a recent Chrome desktop UA.
	UserAgent string
	// Proxy used for all requests. Proxy{Kind:"none"} disables proxying.
	Proxy Proxy
}

func (o *Options) timeout() time.Duration {
	if o.Timeout > 0 {
		return o.Timeout
	}
	return 20 * time.Second
}

func (o *Options) userAgent() string {
	if o.UserAgent != "" {
		return o.UserAgent
	}
	return "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36"
}

// Client is a logged-in session to my.telegram.org. After Login it holds the
// stel_token cookie; use CreateApp to mint an api_id/api_hash pair.
type Client struct {
	http *http.Client
	opts Options
	jar  *simpleJar
}

// New returns an unauthenticated client with the given proxy / timeout.
func New(opts Options) *Client {
	jar := newJar()
	transport := &http.Transport{
		ForceAttemptHTTP2:     true,
		MaxIdleConns:          10,
		IdleConnTimeout:       60 * time.Second,
		TLSHandshakeTimeout:   15 * time.Second,
		ExpectContinueTimeout: 1 * time.Second,
		TLSClientConfig:       &tls.Config{MinVersion: tls.VersionTLS12},
		DialContext: (&net.Dialer{
			Timeout:   15 * time.Second,
			KeepAlive: 30 * time.Second,
		}).DialContext,
	}
	if opts.Proxy.Kind == "socks5" || opts.Proxy.Kind == "socks" {
		// SOCKS5 needs a real dialer; http.Transport.Proxy only handles HTTP.
		addr := fmt.Sprintf("%s:%d", opts.Proxy.Host, opts.Proxy.Port)
		var auth *proxy.Auth
		if opts.Proxy.Username != "" {
			auth = &proxy.Auth{User: opts.Proxy.Username, Password: opts.Proxy.Password}
		}
		if d, err := proxy.SOCKS5("tcp", addr, auth, proxy.Direct); err == nil {
			if cd, ok := d.(proxy.ContextDialer); ok {
				transport.DialContext = cd.DialContext
			} else {
				transport.DialContext = func(ctx context.Context, network, address string) (net.Conn, error) {
					return d.Dial(network, address)
				}
			}
		}
	} else if proxyURL := opts.Proxy.URL(); proxyURL != "" {
		if u, err := url.Parse(proxyURL); err == nil {
			transport.Proxy = http.ProxyURL(u)
		}
	}
	hc := &http.Client{
		Transport: transport,
		Timeout:   opts.timeout(),
		Jar:       jar,
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			// keep cookies + the X-Requested-With header on redirects
			return nil
		},
	}
	return &Client{http: hc, opts: opts, jar: jar}
}

// SendPassword asks my.telegram.org to push a login code to the account that
// owns `phone`. It returns the random_hash needed for the next step.
func (c *Client) SendPassword(ctx context.Context, phone string) (string, error) {
	body := url.Values{"phone": {phone}}.Encode()
	resp, err := c.do(ctx, http.MethodPost, "https://my.telegram.org/auth/send_password", body, xhrHeaders(c.opts.userAgent()))
	if err != nil {
		return "", fmt.Errorf("send_password: %w", err)
	}
	defer resp.Body.Close()
	raw, _ := io.ReadAll(resp.Body)
	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("send_password: status %d body=%s", resp.StatusCode, truncate(string(raw), 200))
	}
	var parsed struct {
		RandomHash string `json:"random_hash"`
		Error      string `json:"error"`
	}
	if err := json.Unmarshal(raw, &parsed); err != nil {
		return "", fmt.Errorf("send_password: parse json: %w (body=%s)", err, truncate(string(raw), 200))
	}
	if parsed.RandomHash == "" {
		msg := parsed.Error
		if msg == "" {
			msg = "no random_hash returned"
		}
		return "", &APIError{Step: "send_password", Message: msg, Body: string(raw)}
	}
	return parsed.RandomHash, nil
}

// Login exchanges the OTP (the code pushed to the user's Telegram app) for a
// stel_token session cookie. After a successful Login the client is fully
// authenticated for /apps.
func (c *Client) Login(ctx context.Context, phone, randomHash, otp string) error {
	body := url.Values{
		"phone":       {phone},
		"random_hash": {randomHash},
		"password":    {otp},
	}.Encode()
	resp, err := c.do(ctx, http.MethodPost, "https://my.telegram.org/auth/login", body, xhrHeaders(c.opts.userAgent()))
	if err != nil {
		return fmt.Errorf("login: %w", err)
	}
	defer resp.Body.Close()
	raw, _ := io.ReadAll(resp.Body)
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("login: status %d body=%s", resp.StatusCode, truncate(string(raw), 200))
	}
	// my.telegram.org returns "true" on success or an error string.
	bodyStr := strings.TrimSpace(string(raw))
	if bodyStr != "true" {
		return &APIError{Step: "login", Message: bodyStr, Body: bodyStr}
	}
	if c.jar.get("stel_token") == "" {
		return errors.New("login: success but no stel_token cookie set")
	}
	return nil
}

// AppFields are the values submitted when creating a new application.
type AppFields struct {
	Title     string
	ShortName string
	URL       string
	Platform  string // android | ios | desktop | web | other
	Desc      string
}

// CreateApp creates a new Telegram application and returns the freshly issued
// api_id and api_hash. It expects the client to already be authenticated.
func (c *Client) CreateApp(ctx context.Context, f AppFields) (apiID, apiHash string, err error) {
	if err := c.ensureAppForm(ctx); err != nil {
		return "", "", err
	}

	// Step 3: fetch /apps and extract the hidden form hash.
	formHash, err := c.fetchAppFormHash(ctx)
	if err != nil {
		return "", "", err
	}

	// Step 4: submit /apps/create.
	createBody := url.Values{
		"hash":          {formHash},
		"app_title":     {f.Title},
		"app_shortname": {f.ShortName},
		"app_url":       {f.URL},
		"app_platform":  {f.Platform},
		"app_desc":      {f.Desc},
	}.Encode()
	resp, err := c.do(ctx, http.MethodPost, "https://my.telegram.org/apps/create", createBody, xhrHeaders(c.opts.userAgent()))
	if err != nil {
		return "", "", fmt.Errorf("create app: %w", err)
	}
	defer resp.Body.Close()
	raw, _ := io.ReadAll(resp.Body)
	if resp.StatusCode != http.StatusOK {
		return "", "", fmt.Errorf("create app: status %d body=%s", resp.StatusCode, truncate(string(raw), 300))
	}
	bodyStr := strings.TrimSpace(string(raw))
	if bodyStr != "true" {
		// Common case: user already has an app; my.telegram.org returns an
		// error string. We still try to scrape /apps in case it succeeded.
		if !strings.Contains(strings.ToLower(bodyStr), "error") {
			// may be a redirect or a "true"-ish value
		}
	}

	// Step 5: fetch /apps again and scrape api_id / api_hash.
	return c.fetchAppCredentials(ctx)
}

// ensureAppForm makes sure the user has an app form to fill (loads /apps once
// quietly). The endpoint initializes the session.
func (c *Client) ensureAppForm(ctx context.Context) error {
	resp, err := c.do(ctx, http.MethodGet, "https://my.telegram.org/apps", "", docHeaders(c.opts.userAgent()))
	if err != nil {
		return fmt.Errorf("load apps page: %w", err)
	}
	defer resp.Body.Close()
	_, _ = io.Copy(io.Discard, resp.Body)
	return nil
}

// fetchAppFormHash parses the hidden <input name="hash" value="..."> from
// /apps. This hash is required by /apps/create.
func (c *Client) fetchAppFormHash(ctx context.Context) (string, error) {
	resp, err := c.do(ctx, http.MethodGet, "https://my.telegram.org/apps", "", docHeaders(c.opts.userAgent()))
	if err != nil {
		return "", fmt.Errorf("fetch apps (hash): %w", err)
	}
	defer resp.Body.Close()
	raw, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	// Fast path: regex over the raw HTML. The page is small.
	re := regexp.MustCompile(`<input[^>]+name=["']hash["'][^>]+value=["']([^"']+)["']`)
	if m := re.FindSubmatch(raw); len(m) == 2 {
		return string(m[1]), nil
	}
	// Fallback: full parse.
	if v, ok := findInputValue(raw, "hash"); ok {
		return v, nil
	}
	return "", &APIError{Step: "fetch_hash", Message: "could not find form hash on /apps", Body: truncate(string(raw), 300)}
}

// fetchAppCredentials parses the two <span class="form-control input-xlarge
// uneditable-input"> elements that hold api_id and api_hash.
func (c *Client) fetchAppCredentials(ctx context.Context) (string, string, error) {
	resp, err := c.do(ctx, http.MethodGet, "https://my.telegram.org/apps", "", docHeaders(c.opts.userAgent()))
	if err != nil {
		return "", "", fmt.Errorf("fetch apps (creds): %w", err)
	}
	defer resp.Body.Close()
	raw, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", "", err
	}
	creds := findUneditableInputs(raw)
	if len(creds) < 2 {
		return "", "", &APIError{
			Step:    "fetch_creds",
			Message: "could not find api_id/api_hash on /apps (app may not have been created)",
			Body:    truncate(string(raw), 300),
		}
	}
	return strings.TrimSpace(creds[0]), strings.TrimSpace(creds[1]), nil
}

// ---- low-level HTTP ----

func (c *Client) do(ctx context.Context, method, target, body string, headers map[string]string) (*http.Response, error) {
	var rdr io.Reader
	if body != "" {
		rdr = strings.NewReader(body)
	}
	req, err := http.NewRequestWithContext(ctx, method, target, rdr)
	if err != nil {
		return nil, err
	}
	for k, v := range headers {
		req.Header.Set(k, v)
	}
	return c.http.Do(req)
}

func xhrHeaders(ua string) map[string]string {
	return map[string]string{
		"accept":             "application/json, text/javascript, */*; q=0.01",
		"accept-language":    "en-US,en;q=0.9",
		"content-type":       "application/x-www-form-urlencoded; charset=UTF-8",
		"origin":             "https://my.telegram.org",
		"referer":            "https://my.telegram.org/auth",
		"sec-fetch-dest":     "empty",
		"sec-fetch-mode":     "cors",
		"sec-fetch-site":     "same-origin",
		"user-agent":         ua,
		"x-requested-with":   "XMLHttpRequest",
	}
}

func docHeaders(ua string) map[string]string {
	return map[string]string{
		"accept":                   "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
		"accept-language":          "en-US,en;q=0.9",
		"referer":                  "https://my.telegram.org/",
		"sec-fetch-dest":           "document",
		"sec-fetch-mode":           "navigate",
		"sec-fetch-site":           "same-origin",
		"sec-fetch-user":           "?1",
		"upgrade-insecure-requests": "1",
		"user-agent":               ua,
	}
}

// ---- HTML helpers ----

// findInputValue returns the value of the first <input name="name"> using a
// real tokenizer (handles attribute order variations).
func findInputValue(raw []byte, name string) (string, bool) {
	tz := html.NewTokenizer(strings.NewReader(string(raw)))
	for {
		tt := tz.Next()
		if tt == html.ErrorToken {
			return "", false
		}
		if tt != html.StartTagToken {
			continue
		}
		tn, hasAttr := tz.TagName()
		if string(tn) != "input" || !hasAttr {
			continue
		}
		var gotName, val string
		for {
			key, value, more := tz.TagAttr()
			if string(key) == "name" && string(value) == name {
				gotName = "1"
			}
			if string(key) == "value" {
				val = string(value)
			}
			if !more {
				break
			}
		}
		if gotName == "1" && val != "" {
			return val, true
		}
	}
}

// findUneditableInputs returns the text of every
// <span class="...uneditable-input..."> in document order.
func findUneditableInputs(raw []byte) []string {
	var out []string
	tz := html.NewTokenizer(strings.NewReader(string(raw)))
	inSpan := false
	for {
		tt := tz.Next()
		if tt == html.ErrorToken {
			return out
		}
		switch tt {
		case html.StartTagToken:
			tn, hasAttr := tz.TagName()
			if string(tn) == "span" && hasAttr {
				for {
					key, val, more := tz.TagAttr()
					if string(key) == "class" && strings.Contains(string(val), "uneditable-input") {
						inSpan = true
					}
					if !more {
						break
					}
				}
			}
		case html.TextToken:
			if inSpan {
				out = append(out, string(tz.Text()))
			}
		case html.EndTagToken:
			tn, _ := tz.TagName()
			if string(tn) == "span" {
				inSpan = false
			}
		}
	}
}

// ---- errors ----

// APIError carries the failing step plus the raw response body so the bot can
// show a useful message to the user / admin.
type APIError struct {
	Step    string
	Message string
	Body    string
}

func (e *APIError) Error() string {
	return fmt.Sprintf("mytelegram[%s]: %s", e.Step, e.Message)
}

// ---- misc ----

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

// ---- tiny cookie jar ----
//
// We only ever talk to my.telegram.org and only need the stel_token cookie, so
// a purpose-built jar is simpler and clearer than wiring net/http/cookiejar.

type simpleJar struct {
	cookies map[string]string
}

func newJar() *simpleJar { return &simpleJar{cookies: map[string]string{}} }

func (j *simpleJar) SetCookies(u *url.URL, cookies []*http.Cookie) {
	for _, c := range cookies {
		j.cookies[c.Name] = c.Value
	}
}
func (j *simpleJar) Cookies(u *url.URL) []*http.Cookie {
	out := make([]*http.Cookie, 0, len(j.cookies))
	for k, v := range j.cookies {
		out = append(out, &http.Cookie{Name: k, Value: v})
	}
	return out
}
func (j *simpleJar) get(name string) string { return j.cookies[name] }
