let getRootRequirementsConfig = require('./get-root-requirements-config')
let getLambdaDeps = require('./get-lambda-deps')

module.exports = function treeshakePython (pyDirs, params) {
  let { cwd, inventory, update } = params

  // Generated manifests to be hydrated later (if there are no parsing failures)
  let installing = []

  // Userland files that could not be parsed
  let failures = []

  // TODO: get / match root deps?

  // Get root config (if any)
  let requirementsConfig = getRootRequirementsConfig(inventory)

  // Stats
  let projectDirs = 0
  let projectFiles = 0
  let pyDeps = 0

  // TODO: Aggregate shared + views deps?

  pyDirs.forEach(dir => {
    projectDirs++
    let lambda = inventory.inv.lambdasBySrcDir[dir]
    if (Array.isArray(lambda)) lambda = lambda[0] // Multi-tenant Lambda check
    let { config, name, pragma } = lambda
    let { runtime } = config

    try {
      let result = getLambdaDeps({ dir, inventory, runtime })
      let { deps, files } = result
      projectFiles += files.length
      failures = failures.concat(result.failures)

      // Exit now if there are no deps to write or the Lambda is in the project root
      if (!deps.length) return
      if (dir === cwd && deps.length) {
        update.warn(`@${pragma} ${name} handler in project root skipped during Lambda treeshaking`)
        return
      }
      pyDeps += deps.length

      // Build the manifest
      let dependencies = deps.sort().join('\n')
      let line = '#   - '
      let fileList = line + files.sort().join('\n' + line)

      let lambdaRequirements = `# _arc: autoinstall,
# _module: hydrate,
# _date: ${new Date().toISOString()},
# _parsed:
${fileList}
# description: This file was generated by Architect, and placed in vendor/ to aid in debugging; if you found file in your function directory, you can safely remove it
${requirementsConfig}${dependencies}
`
      let params = {
        dir,
        file: 'requirements.txt',
        remove: [ 'requirements.txt' ], // Identify files for later removal
        data: lambdaRequirements,
      }
      installing.push(params)
    }
    catch (err) {
      update.error(`Error autoinstalling dependencies in ${dir}`)
      throw err
    }
  })

  // Halt hydration (and deployment) if there are dependency determination issues
  if (failures.length) {
    update.error('Python parsing error(s), could not automatically determine dependencies')
    failures.forEach(({ file, error }) => {
      console.log('File:', file)
      console.log(error)
    })
    process.exit(1)
  }

  return {
    installing,
    projectDirs,
    projectFiles,
    pyDeps,
  }
}
