package uv

import (
	
	
	
	
)

// newFallbackReader creates a new fallbackReader for the given io.Reader.
func ( io.Reader) (pollReader, error) {
	return &fallbackReader{
		reader:     bufio.NewReader(),
		cancelChan: make(chan struct{}),
		dataChan:   make(chan struct{}, 1),
	}, nil
}

// fallbackReader implements pollReader using goroutines and buffered I/O.
// This is a fallback implementation that works on all platforms.
type fallbackReader struct {
	reader     *bufio.Reader
	cancelChan chan struct{}
	dataChan   chan struct{}
	mu         sync.Mutex
	canceled   bool
	started    bool
}

// Read reads data from the underlying reader.
func ( *fallbackReader) ( []byte) (int, error) {
	.mu.Lock()
	if .canceled {
		.mu.Unlock()
		return 0, ErrCanceled
	}
	.mu.Unlock()

	,  := .reader.Read()
	// If we get an error during a concurrent cancel, prefer ErrCanceled
	if  != nil {
		.mu.Lock()
		if .canceled {
			.mu.Unlock()
			return 0, ErrCanceled
		}
		.mu.Unlock()
	}
	return , 
}

// Poll waits for data to be available to read with the given timeout.
// This implementation starts a background goroutine to check for buffered
// data availability.
func ( *fallbackReader) ( time.Duration) (bool, error) {
	.mu.Lock()
	if .canceled {
		.mu.Unlock()
		return false, ErrCanceled
	}

	// Start the background reader goroutine if not already started
	if !.started {
		.started = true
		go .checkBuffered()
	}
	.mu.Unlock()

	if  < 0 {
		// Wait indefinitely
		select {
		case <-.dataChan:
			// Put it back for next poll/read
			select {
			case .dataChan <- struct{}{}:
			default:
			}
			return true, nil
		case <-.cancelChan:
			return false, ErrCanceled
		}
	}

	// Wait with timeout
	 := time.NewTimer()
	defer .Stop()

	select {
	case <-.dataChan:
		// Put it back for next poll/read
		select {
		case .dataChan <- struct{}{}:
		default:
		}
		return true, nil
	case <-.C:
		return false, nil
	case <-.cancelChan:
		return false, ErrCanceled
	}
}

// checkBuffered runs in a background goroutine to signal when data is available.
func ( *fallbackReader) () {
	for {
		select {
		case <-.cancelChan:
			return
		default:
		}

		// Check if data is buffered
		.mu.Lock()
		if .canceled {
			.mu.Unlock()
			return
		}
		.mu.Unlock()

		// Peek at one byte to check if data is available
		// This will block until data arrives
		,  := .reader.Peek(1)
		if  != nil {
			// If error (including EOF), stop the goroutine
			return
		}

		// Signal that data is available
		select {
		case .dataChan <- struct{}{}:
		case <-.cancelChan:
			return
		}

		// Wait a bit before checking again to avoid busy loop
		time.Sleep(10 * time.Millisecond)
	}
}

// Cancel cancels any ongoing poll or read operations.
func ( *fallbackReader) () bool {
	.mu.Lock()
	if .canceled {
		.mu.Unlock()
		return false
	}
	.canceled = true
	.mu.Unlock()

	close(.cancelChan)
	return true
}

// Close closes the reader and releases any resources.
func ( *fallbackReader) () error {
	.Cancel()
	return nil
}