import * as fs from "fs"
import * as path from "path"
import { ContributorInfo, DataJSON } from "./info"

const main = async () => {
  const readmePath = path.join(`..`, `..`, `README.md`)
  const contentBuf = fs.readFileSync(readmePath)
  const beginPattern = `<!-- BEGIN AUTOGENERATED CONTRIBUTORS -->\n`
  const endPattern = `\n<!-- END AUTOGENERATED CONTRIBUTORS -->`

  const beginIndex = contentBuf.indexOf(beginPattern)
  const endIndex = contentBuf.indexOf(endPattern)
  if (beginIndex < 0 || endIndex < 0 || beginIndex >= endIndex) {
    throw new Error(`no valid patterns in readme: beginIndex=${beginIndex}, endIndex=${endIndex}`)
  }

  const contributors = buildContributorsContent()
  const rewrittenContent =
    contentBuf.slice(0, beginIndex + beginPattern.length).toString() + contributors + contentBuf.slice(endIndex).toString()

  // it's not atomic, TODO: use rename
  fs.writeFileSync(readmePath, rewrittenContent)
}

const colPerRow = 7
const rowsVisible = 5

const buildContributorsTable = (contributors: ContributorInfo[]): string => {
  type Contributors = ContributorInfo[]
  const rows: Contributors[] = []
  for (let i = 0; i < contributors.length; ) {
    rows.push(contributors.slice(i, i + colPerRow))
    i += colPerRow
  }

  return `<table>
${rows
  .map(
    (row) =>
      `<tr>\n${row
        .map(
          (c) =>
            `  <td align="center"><a href="${
              c.websiteUrl ? (c.websiteUrl.startsWith("http") ? c.websiteUrl : `https://${c.websiteUrl}`) : `https://github.com/${c.login}`
            }?utm_source=golangci-lint-contributors"><img src="${c.avatarUrl}" width="100px;" alt=""/><br /><sub><b>${
              c.name ? c.name : `@${c.login}`
            }</b></sub></a></td>`
        )
        .join(`\n`)}\n</tr>`
  )
  .join(`\n`)}
</table>`
}

const buildContributorsContent = (): string => {
  const data: DataJSON = JSON.parse(fs.readFileSync(`contributors.json`).toString())

  const visibleCount = colPerRow * rowsVisible
  const hiddenCount = data.contributors.length - visibleCount

  return `<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
### Core Team

<details>
<summary>About core team</summary>

The GolangCI Core Team is a group of contributors that have demonstrated a lasting enthusiasm for the project and community.
The GolangCI Core Team has GitHub admin privileges on the repo.

#### Responsibilities
The Core Team has the following responsibilities:

1. Being available to answer high-level questions about vision and future.
2. Being available to review longstanding/forgotten pull requests.
3. Occasionally check issues, offer input, and categorize with GitHub issue labels.
4. Looking out for up-and-coming members of the GolangCI community who might want to serve as Core Team members.
5. Note that the Core Team – and all GolangCI contributors – are open source volunteers; membership on the Core Team is expressly not an obligation. The Core Team is distinguished as leaders in the community and while they are a good group to turn to when someone needs an answer to a question, they are still volunteering their time, and may not be available to help immediately.

</details>

${buildContributorsTable(data.coreTeam)}

### Team

${buildContributorsTable(data.contributors.slice(0, visibleCount))}

<details>
<summary>And ${hiddenCount} more our team members</summary>

${buildContributorsTable(data.contributors.slice(visibleCount))}

</details>

<!-- markdownlint-enable -->
<!-- prettier-ignore-end -->`
}

main()
