package common

import (
	"strings"

	contractevents "bit.admedia.com/scm/ad/adpilot-indexing-code-parser.com/internal/contracts/events"
)

const (
	DefaultChunkLines   = 100
	DefaultChunkOverlap = 20
)

// LineWindowChunks splits source into overlapping line-window chunks for fallback retrieval.
func LineWindowChunks(source []byte, filePath, language string, window, overlap int) []contractevents.CodeChunk {
	if window <= 0 {
		window = DefaultChunkLines
	}
	if overlap < 0 {
		overlap = 0
	}
	if overlap >= window {
		overlap = window / 4
	}

	lines := strings.Split(string(source), "\n")
	if len(lines) == 0 {
		return nil
	}

	var chunks []contractevents.CodeChunk
	step := window - overlap
	if step < 1 {
		step = 1
	}

	for start := 0; start < len(lines); start += step {
		end := start + window
		if end > len(lines) {
			end = len(lines)
		}
		chunkNum := len(chunks) + 1
		symbolID := SymbolNodeID(filePath, fmtChunkName(chunkNum))
		chunks = append(chunks, contractevents.CodeChunk{
			ChunkID:    ChunkID(symbolID),
			SymbolName: fmtChunkName(chunkNum),
			SymbolType: contractevents.SymbolTypeVariable,
			StartLine:  start + 1,
			EndLine:    end,
		})
		if end >= len(lines) {
			break
		}
	}
	return chunks
}

func fmtChunkName(n int) string {
	return "chunk_" + itoa(n)
}

func itoa(n int) string {
	if n == 0 {
		return "0"
	}
	var buf [20]byte
	i := len(buf)
	for n > 0 {
		i--
		buf[i] = byte('0' + n%10)
		n /= 10
	}
	return string(buf[i:])
}
