package telegram

import (
	
	
	
	

	
	
	
	

	

	
	
	
	
	
	
	
	
	
	
	
	
	
)

// UpdateHandler will be called on received updates from Telegram.
type UpdateHandler interface {
	Handle(ctx context.Context, u tg.UpdatesClass) error
}

// UpdateHandlerFunc type is an adapter to allow the use of
// ordinary function as update handler.
//
// UpdateHandlerFunc(f) is an UpdateHandler that calls f.
type UpdateHandlerFunc func(ctx context.Context, u tg.UpdatesClass) error

// Handle calls f(ctx, u)
func ( UpdateHandlerFunc) ( context.Context,  tg.UpdatesClass) error {
	return (, )
}

type clientStorage interface {
	Load(ctx context.Context) (*session.Data, error)
	Save(ctx context.Context, data *session.Data) error
}

type clientConn interface {
	Run(ctx context.Context) error
	Invoke(ctx context.Context, input bin.Encoder, output bin.Decoder) error
	Ping(ctx context.Context) error
}

// Client represents a MTProto client to Telegram.
type Client struct {
	// Put migration in the header of the structure to ensure 64-bit alignment,
	// otherwise it will cause the atomic operation of connsCounter to panic.
	// DO NOT change the order of members arbitrarily.
	// Ref: https://pkg.go.dev/sync/atomic#pkg-note-BUG

	// Connection factory fields.
	connsCounter   atomic.Int64
	create         connConstructor        // immutable
	resolver       dcs.Resolver           // immutable
	onDead         func(error)            // immutable
	newConnBackoff func() backoff.BackOff // immutable
	defaultMode    manager.ConnMode       // immutable
	// onConnectionState is called on primary connection state change.
	onConnectionState func(ConnectionState) // immutable
	// connDC is the DC of conn, set by createPrimaryConn. Guarded by connMux.
	connDC int
	// onConnectionStateEvent is onConnectionState with the DC ID.
	onConnectionStateEvent func(ConnectionStateEvent) // immutable
	// onConnDead is onDead with the DC ID and connection kind.
	onConnDead func(ConnDeadEvent) // immutable

	// Migration state.
	migrationTimeout time.Duration // immutable
	filePoolSize     int64         // immutable
	// requestTimeout returns response deadline of request, may be nil.
	requestTimeout func(input bin.Encoder) time.Duration // immutable
	// restartSem serializes restarts on request timeout, a 1-slot semaphore
	// that waiters can leave when their context is done.
	restartSem chan struct{}
	migration  chan struct{}

	// tg provides RPC calls via Client. Uses invoker below.
	tg *tg.Client // immutable
	// invoker implements tg.Invoker on top of Client and mw.
	invoker tg.Invoker // immutable
	// mw is list of middlewares used in invoker, can be blank.
	mw []Middleware // immutable

	// Telegram device information.
	device DeviceConfig // immutable

	// Schema layer requested via invokeWithLayer.
	layer int // immutable

	// MTProto options.
	opts mtproto.Options // immutable
	// serverTime is the server time offset shared by all connections.
	serverTime *mtproto.ServerTime // immutable
	// serverTimeSet reports whether Options.ServerTimeOffset was set, so the
	// persisted offset doesn't override it.
	serverTimeSet bool // immutable

	// DCList state.
	// Domain list (for websocket)
	domains map[int]string // immutable
	// Denotes to use Test DCs.
	testDC bool // immutable

	// Connection state. Guarded by connMux.
	session *pool.SyncSession
	cfg     *manager.AtomicConfig
	conn    clientConn
	// connChanged is closed and re-created on every primary connection
	// replacement, letting invokeConn wait for reconnect and retry.
	connChanged chan struct{}
	connBackoff atomic.Pointer[backoff.BackOff]
	connMux     sync.Mutex

	// Restart signal channel.
	restart chan struct{} // immutable

	// auth tracks authorization for OnAuthLost.
	auth       authState
	onAuthLost func(ctx context.Context, err error) error // immutable
	// authLost receives error to stop Run on lost authorization.
	authLost chan error

	// onFrozen is called when a frozen error is confirmed by app config.
	onFrozen func(ctx context.Context, state FreezeState) // immutable
	// freezeChecked is when the freeze state was last checked after a
	// frozen error, guarded by freezeMux.
	freezeChecked time.Time
	freezeMux     sync.Mutex

	// Connections to non-primary DC.
	// subConns are pools for *_MIGRATE redirects (invokeSub).
	subConns *dcPoolCache
	// filePools are pools returned by FileDC.
	filePools *dcPoolCache
	// fileInvokers are FileDC invokers wrapped with middlewares.
	fileInvokers    map[int]tg.Invoker
	fileInvokersMux sync.Mutex
	// Shared CDN pools and handle references.
	cdnPools cdnPoolManager
	// sessions stores regular non-primary DC sessions.
	sessions map[int]*pool.SyncSession
	// cdnSessions stores session state for CDN pools separately from regular DCs.
	cdnSessions map[int]*pool.SyncSession
	// droppedKeys holds the ids of auth keys dropped per DC after
	// ErrPFSDropKeysRequired, so that a connection still running on a dropped
	// key can't store it back (see storeDCSess). Guarded by sessionsMux.
	droppedKeys map[int][8]byte
	// dcAuthorized holds, per non-home DC, the id of the auth key the
	// authorization was transferred to, so that pools using it skip the
	// transfer and the key is persisted. Guarded by sessionsMux.
	dcAuthorized map[int][8]byte
	// dcAuthPending holds DCs whose authorization was transferred before the
	// session (key) of the new connection was reported; the mark is set when
	// it is. Guarded by sessionsMux.
	dcAuthPending map[int]bool
	// sessionStates are server session slots per DC, reused across
	// reconnects. Guarded by sessionsMux.
	sessionStates map[int][]*mtproto.SessionState
	sessionsMux   sync.Mutex
	// primarySessions counts new server sessions of the primary connection.
	primarySessions atomic.Int64
	// saveMux serializes load-modify-save of the stored session.
	saveMux sync.Mutex
	// selfID and selfBot are the authorized user, if known (selfID != 0).
	selfID  atomic.Int64
	selfBot atomic.Bool
	// CDN public keys loaded from help.getCdnConfig and cached per CDN DC.
	cdnKeys     []PublicKey
	cdnKeysByDC map[int][]PublicKey
	cdnKeysSet  bool
	// cdnKeysGen increments on cache invalidation to avoid storing stale
	// singleflight result after fingerprint miss.
	cdnKeysGen  uint64
	cdnKeysMux  sync.Mutex
	cdnKeysLoad singleflight.Group

	// Wrappers for external world, like logs or PRNG.
	rand  io.Reader   // immutable
	log   log.Helper  // immutable
	clock clock.Clock // immutable

	// life is the state of Start, Close, Done and Wait.
	life lifecycle

	// Client context. Will be canceled by Run on exit.
	ctx    context.Context
	cancel context.CancelFunc

	// Client config.
	appID   int    // immutable
	appHash string // immutable
	// allowCDN is the explicit downloader policy copied from Options.AllowCDN.
	allowCDN bool // immutable
	// downloadSchedulers are per-DC download schedulers, nil if
	// Options.DownloadScheduler is not set.
	downloadSchedulers *downloadSchedulers // immutable
	// downloader is the instrumented base of Client.Downloader, nil if the
	// client is not created by NewClient.
	downloader *downloader.Downloader // immutable
	// Session storage.
	storage clientStorage // immutable, nillable

	// Ready signal channel, sends signal when client connection is ready.
	// Resets on reconnect.
	ready *tdsync.ResetReady // immutable

	// Telegram updates handler.
	updateHandler UpdateHandler // immutable
	// Denotes that no update mode is enabled.
	noUpdatesMode bool // immutable

	// Tracing.
	tracer trace.Tracer
	// metrics are OpenTelemetry instruments, see meters.
	metrics *clientMetrics // immutable

	// onTransfer is called in transfer.
	onTransfer AuthTransferHandler

	// onSelfError is called on error calling Self().
	onSelfError func(ctx context.Context, err error) error

	// onSelfSuccess is called on success calling Self().
	onSelfSuccess func(self *tg.User)
}

// NewClient creates new unstarted client.
func ( int,  string,  Options) *Client {
	.setDefaults()

	 := manager.ConnModeUpdates
	if .NoUpdates {
		 = manager.ConnModeData
	}
	 := &Client{
		rand:               .Random,
		log:                log.For(.Logger),
		appID:              ,
		appHash:            ,
		allowCDN:           .AllowCDN,
		downloadSchedulers: newDownloadSchedulers(.DownloadScheduler, .MeterProvider),
		updateHandler:      .UpdateHandler,
		session: pool.NewSyncSession(pool.Session{
			DC: .DC,
		}),
		domains: .DCList.Domains,
		testDC:  .DCList.Test,
		cfg: manager.NewAtomicConfig(tg.Config{
			DCOptions: .DCList.Options,
		}),
		create:                 defaultConstructor(),
		resolver:               .Resolver,
		defaultMode:            ,
		newConnBackoff:         .ReconnectionBackoff,
		onDead:                 .OnDead,
		onConnectionState:      .OnConnectionState,
		onConnectionStateEvent: .OnConnectionStateEvent,
		onConnDead:             .OnConnDead,
		clock:                  .Clock,
		device:                 .Device,
		layer:                  .Layer,
		migrationTimeout:       .MigrationTimeout,
		filePoolSize:           .FilePoolSize,
		requestTimeout:         .RequestTimeout,
		noUpdatesMode:          .NoUpdates,
		mw:                     .Middlewares,
		onTransfer:             .OnTransfer,
		onSelfError:            .OnSelfError,
		onSelfSuccess:          .OnSelfSuccess,
		onAuthLost:             .OnAuthLost,
		onFrozen:               .OnFrozen,
	}
	if .TracerProvider != nil {
		.tracer = .TracerProvider.Tracer(oteltg.Name)
	}
	,  := newClientMetrics(.MeterProvider)
	if  != nil {
		.log.Warn(context.Background(), "Create metrics, metrics are disabled", log.Error())
		 = noopClientMetrics()
	}
	.metrics = 
	.downloader = newClientDownloader(.allowCDN, .MeterProvider, .Logger)
	.init()

	// Including version into client logger to help with debugging.
	if  := version.GetVersion();  != "" {
		.log = .log.With(log.String("v", ))
	}

	if .SessionStorage != nil {
		.storage = &session.Loader{
			Storage: .SessionStorage,
		}
	}

	.serverTime = mtproto.NewServerTime(.Clock, .ServerTimeOffset)
	.serverTimeSet = .ServerTimeOffset != 0
	if .MessageID == nil {
		.MessageID = proto.NewMessageIDGen(.serverTime.Now)
	}
	.opts = mtproto.Options{
		PublicKeys:        .PublicKeys,
		Random:            .Random,
		Logger:            .Logger,
		AckBatchSize:      .AckBatchSize,
		AckInterval:       .AckInterval,
		RetryInterval:     .RetryInterval,
		MaxRetries:        .MaxRetries,
		CompressThreshold: .CompressThreshold,
		MessageID:         .MessageID,
		ExchangeTimeout:   .ExchangeTimeout,
		DialTimeout:       .DialTimeout,
		PingInterval:      .PingInterval,
		PingTimeout:       .PingTimeout,
		// Forward PFS toggles into low-level mtproto connection.
		EnablePFS:  .EnablePFS,
		TempKeyTTL: .TempKeyTTL,
		Clock:      .Clock,
		ServerTime: .serverTime,

		Types: getTypesMapping(),

		Tracer:     .tracer,
		WireTracer: .WireTracer,
	}
	.conn = .createPrimaryConn(nil)

	return 
}

// replaceConn replaces primary connection and notifies invokers waiting for
// reconnection (see invokeConn).
//
// Caller must hold connMux.
func ( *Client) ( clientConn) {
	.conn = 
	close(.connChanged)
	.connChanged = make(chan struct{})
}

// init sets fields which needs explicit initialization, like maps or channels.
func ( *Client) () {
	if .domains == nil {
		.domains = map[int]string{}
	}
	if .cfg == nil {
		.cfg = manager.NewAtomicConfig(tg.Config{})
	}
	.ready = tdsync.NewResetReady()
	.connChanged = make(chan struct{})
	.restart = make(chan struct{})
	.authLost = make(chan error, 1)
	.restartSem = make(chan struct{}, 1)
	.migration = make(chan struct{}, 1)
	.sessions = map[int]*pool.SyncSession{}
	.cdnSessions = map[int]*pool.SyncSession{}
	.droppedKeys = map[int][8]byte{}
	.dcAuthorized = map[int][8]byte{}
	.dcAuthPending = map[int]bool{}
	.sessionStates = map[int][]*mtproto.SessionState{}
	.subConns = newDCPoolCache(1, poolKindMigrate)
	if .filePoolSize <= 0 {
		.filePoolSize = defaultFilePoolSize
	}
	.filePools = newDCPoolCache(.filePoolSize, poolKindFile)
	.fileInvokers = map[int]tg.Invoker{}
	.cdnPools = newCDNPoolManager()
	// CDN key cache is cold-started and filled lazily on first CDN pool create.
	.cdnKeys = nil
	.cdnKeysByDC = nil
	.cdnKeysSet = false
	.cdnKeysGen = 0
	.cdnKeysLoad = singleflight.Group{}
	.invoker = measuredInvoker{
		client: ,
		next:   chainMiddlewares(InvokeFunc(.invokeDirect), .mw...),
	}
	.tg = tg.NewClient(.invoker)
}

// ServerTimeOffset returns the server time minus local time observed by the
// client, to be passed as Options.ServerTimeOffset on the next start. It is
// zero until the first connection to the server.
func ( *Client) () time.Duration {
	return .serverTime.Offset()
}