// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========

import type { PostHogAccessor } from '../../accessor/posthog.ts'
import type { IndexCacheStore } from '../../cache/index/store.ts'
import { PathSpec } from '../../types.ts'
import { readdir } from './readdir.ts'

const SCOPE_LIMIT = 1024

function fnmatch(name: string, pattern: string): boolean {
  let regex = '^'
  for (let i = 0; i < pattern.length; i++) {
    const c = pattern[i]
    if (c === undefined) break
    if (c === '*') regex += '.*'
    else if (c === '?') regex += '.'
    else if (c === '[') {
      const close = pattern.indexOf(']', i)
      if (close === -1) regex += '\\['
      else {
        regex += '[' + pattern.slice(i + 1, close) + ']'
        i = close
      }
    } else if ('.+()|\\^$'.includes(c)) regex += '\\' + c
    else regex += c
  }
  regex += '$'
  return new RegExp(regex).test(name)
}

export async function resolveGlob(
  accessor: PostHogAccessor,
  paths: readonly PathSpec[],
  index?: IndexCacheStore,
): Promise<PathSpec[]> {
  const result: PathSpec[] = []
  for (const p of paths) {
    if (p.resolved) {
      result.push(p)
    } else if (p.pattern !== null) {
      const entries = await readdir(accessor, p.dir, index)
      const pat = p.pattern
      const matched = entries
        .filter((e) => {
          const tail = e.split('/').pop() ?? ''
          return fnmatch(tail, pat)
        })
        .map(
          (e) =>
            new PathSpec({
              original: e,
              directory: p.directory,
              prefix: p.prefix,
            }),
        )
      result.push(...matched.slice(0, SCOPE_LIMIT))
    } else {
      result.push(p)
    }
  }
  return result
}
