package downloader

import (
	
	
	
	

	
	

	
)

// Builder is a download builder.
type Builder struct {
	downloader *Downloader

	schema schema
	hashes []tg.FileHash
	// verify controls legacy outer verifier (reader + verifier queue).
	// CDN redirect path has mandatory protocol-level verification in cdn schema,
	// independent from this flag.
	verify  bool
	threads int
	// scheduler overrides Downloader scheduler, if set.
	scheduler *Scheduler

	// offset is the offset to start download from (WithOffset).
	offset int64
	// size is the known file size, zero if unknown (WithSize).
	size int64
	// progress is called after each written part (WithProgress).
	progress ProgressFunc
}

// ProgressFunc is called after each written part with the offset of the end
// of downloaded data, counting from the start of the file (including the
// offset set by Builder.WithOffset), and the file size if known (see
// Builder.WithSize), zero otherwise.
//
// Calls are not concurrent.
type ProgressFunc func(done, total int64)

func ( *Downloader,  schema) *Builder {
	return &Builder{
		schema:     ,
		threads:    1,
		downloader: ,
	}
}

// WithThreads sets downloading goroutines limit.
func ( *Builder) ( int) *Builder {
	if  > 0 {
		.threads = 
	}
	return 
}

// WithRetryHandler sets callback for transient download errors that are retried
// internally.
//
// Handler can be called concurrently from download workers.
func ( *Builder) ( RetryHandler) *Builder {
	 = .downloader.obs.wrapRetry()
	switch s := .schema.(type) {
	case master:
		.retryHandler = 
		.schema = 
	case web:
		.retryHandler = 
		.schema = 
	case *cdn:
		.retryHandler = 
	}

	return 
}

// WithVerify controls global hash verification behavior.
//
// `true` enables classic verifier reader (preloads hash queue and validates all
// chunks, both legacy and CDN).
// `false` disables classic verifier reader.
//
// If not called explicitly:
// - non-CDN path preserves old behavior (no upfront hash requests);
// - CDN path enables strict inline CDN verification after redirect.
//
// Use WithVerify(true) to force verifier-queue mode on all paths.
func ( *Builder) ( bool) *Builder {
	.verify = 
	return 
}

// WithOffset sets offset to start download from, e.g. to resume a partially
// downloaded file. Data before offset is not downloaded.
//
// Offset must be divisible by the part size (see Downloader.WithPartSize),
// unless verification is enabled via WithVerify(true), which only requires
// 4KB alignment: the hash window containing offset is downloaded whole to
// verify it, and data before offset is dropped.
//
// Stream writes data from offset to the start of io.Writer, Parallel writes
// it at the same offsets of io.WriterAt, and ToPath keeps existing file
// content before offset.
func ( *Builder) ( int64) *Builder {
	.offset = 
	return 
}

// WithSize sets known file size (e.g. Document.Size), so download stops
// requesting parts at the end of file instead of probing past it, and
// progress reports the total.
func ( *Builder) ( int64) *Builder {
	if  > 0 {
		.size = 
	}
	return 
}

// WithProgress sets callback called after each written part.
func ( *Builder) ( ProgressFunc) *Builder {
	.progress = 
	return 
}

const offsetAlign = 4 * 1024

func ( *Builder) () error {
	if .offset < 0 {
		return errors.Errorf("invalid offset %d", .offset)
	}
	if .offset%offsetAlign != 0 {
		return errors.Errorf("offset %d is not divisible by %d", .offset, offsetAlign)
	}
	if !.verify && .downloader.partSize > 0 && .offset%int64(.downloader.partSize) != 0 {
		return errors.Errorf("offset %d is not divisible by part size %d", .offset, .downloader.partSize)
	}
	return nil
}

func ( *Builder) ( master,  bool) *Builder {
	 := *
	 := 
	// Keep explicit switch in schema to guarantee old request path when
	// CDN is disabled or unavailable.
	.allowCDN = 
	.schema = 
	.hashes = nil
	return &
}

func ( *Builder) ( master,  CDNProvider) *Builder {
	// Enable redirect errors on master schema (`upload.fileCdnRedirect`) while
	// still serving regular files from master when redirect is not required.
	.allowCDN = true

	 := *
	// Avoid outer verifier on default path to keep non-redirect requests
	// equivalent to legacy master flow; CDN schema still verifies redirected
	// chunks inline according to Telegram CDN protocol.
	 := !.verify
	.hashes = nil
	.schema = newCDNSchema(
		,
		,
		.downloader.pool,
		int64(.threads),
		,
		.retryHandler,
	)
	return &
}

func ( *Builder) () bool {
	// CDN redirect flow is explicit-only to avoid hidden behavior changes and
	// preserve backwards compatibility for callers that never opted in.
	if .downloader.allowCDN == nil {
		return false
	}
	return *.downloader.allowCDN
}

func ( schema) func() error {
	if ,  := .(interface{ () error });  {
		return .
	}
	return nil
}

func ( *Builder) () ( *Builder,  func() error,  error) {
	if  := .validate();  != nil {
		return nil, nil, 
	}
	,  := .schema.(master)
	if ! {
		return , closeSchema(.schema), nil
	}

	// Fast path compatibility guarantee:
	// if CDN is not explicitly allowed we keep legacy master flow exactly as is,
	// without CDN pool creation and without extra hash requests.
	if !.shouldAllowCDN() {
		 := .prepareMaster(, false)
		return , closeSchema(.schema), nil
	}

	// Even with AllowCDN=true, fallback to legacy master flow if client does not
	// provide CDN transport factory.
	,  := .client.(CDNProvider)
	if ! {
		 := .prepareMaster(, false)
		return , closeSchema(.schema), nil
	}

	 := .prepareCDNPath(, )
	return , closeSchema(.schema), nil
}

func ( *Builder) () *reader {
	var  *reader
	if .verify {
		 := newVerifier(.schema, .hashes...)
		.start(.offset)
		 = verifiedReader(.schema, )
		.start = .offset
	} else {
		 = plainReader(.schema, .downloader.partSize)
		.offset = .offset
	}
	.size = .size
	.scheduler = .downloader.scheduler
	if .scheduler != nil {
		.scheduler = .scheduler
	}
	return 
}

// start returns context of a download, reporting its start.
func ( *Builder) ( context.Context) context.Context {
	 := .downloader.obs
	if  == nil {
		return 
	}
	if .offset > 0 {
		.resume(, .offset)
	}
	return .with()
}

func ( *Builder) () sink {
	return sink{
		done:     .offset,
		total:    .size,
		progress: .progress,
	}
}

// Stream downloads file to given io.Writer.
// NB: in this mode download can't be parallel.
func ( *Builder) ( context.Context,  io.Writer) ( tg.StorageFileTypeClass,  error) {
	 = .start()
	defer func() { .downloader.obs.download(, ) }()
	, ,  := .prepare()
	if  != nil {
		return nil, 
	}
	defer func() {
		if  != nil {
			multierr.AppendInto(&, ())
		}
	}()
	,  := .downloader.stream(, .reader(), .sink(), )
	return , 
}

// Parallel downloads file to given io.WriterAt.
func ( *Builder) ( context.Context,  io.WriterAt) ( tg.StorageFileTypeClass,  error) {
	 = .start()
	defer func() { .downloader.obs.download(, ) }()
	, ,  := .prepare()
	if  != nil {
		return nil, 
	}
	defer func() {
		if  != nil {
			multierr.AppendInto(&, ())
		}
	}()

	,  := .downloader.parallel(, .reader(), .sink(), .threads, )
	return , 
}

// ToPath downloads file to given path.
//
// If offset is set (see WithOffset), existing file is not truncated, so data
// before offset is kept. If size is set (see WithSize), the file is truncated
// to it after a successful download.
func ( *Builder) ( context.Context,  string) ( tg.StorageFileTypeClass,  error) {
	 := os.O_RDWR | os.O_CREATE | os.O_TRUNC
	if .offset > 0 {
		 = os.O_RDWR | os.O_CREATE
	}
	,  := os.OpenFile(filepath.Clean(), , 0o666)
	if  != nil {
		return nil, errors.Wrap(, "create output file")
	}
	defer func() {
		multierr.AppendInto(&, .Close())
	}()

	,  := .Parallel(, )
	if  != nil {
		return , 
	}
	if .size > 0 {
		// Drop stale data past the end of file, e.g. from a longer .part file.
		if  := .Truncate(.size);  != nil {
			return , errors.Wrap(, "truncate output file")
		}
	}
	return , nil
}