
import { each } from 'jostraca'

import { KIT, nom } from '@voxgig/apidef'

import { isConsumer } from './alongside'
import { kindCollection } from './kindCollection'
import { modelText } from './text'

const PUBLISHER = 'Voxgig'
const PUBLISHER_URL = 'https://voxgig.com'
const SECURITY_EMAIL = 'security@voxgig.com'
const GENERATOR_URL = 'https://github.com/voxgig/sdkgen'

const LANG_LABEL: Record<string, string> = {
  ts: 'TypeScript',
  js: 'JavaScript',
  py: 'Python',
  php: 'PHP',
  rb: 'Ruby',
  lua: 'Lua',
  go: 'Go',
  'go-cli': 'Go CLI',
  'go-mcp': 'Go MCP server',
  'py-data': 'Python Data',
}

function langLabel(target: string): string {
  return LANG_LABEL[target] || target
}


function originName(model: any, target: string): string {
  const orig = model?.main?.[KIT]?.target?.[target]?.origname
  return (null != orig && '' !== orig) ? String(orig) : target
}

function sdkName(slug: string): string {
  return slug.endsWith('-sdk') ? slug : `${slug}-sdk`
}


function repoInfo(model: any) {
  const slug = model.name
  const origin = model.origin || 'voxgig-sdk'

  const declared = (model && model.main && model.main[KIT] && model.main[KIT].repo) || {}

  const host = '' === (declared.host || '') ? 'github.com' : (declared.host || 'github.com')
  const path = '' === (declared.path || '') ? `${origin}/${sdkName(slug)}` : String(declared.path)

  const seg = path.split('/')
  const repo = seg[seg.length - 1]

  const repoUrl = `https://${host}/${path}`
  const pages = repoPages(host, repoUrl)

  return {
    slug,
    origin,
    host,
    path,
    repo,
    repoUrl,
    hostName: pages.name,
    issuesUrl: pages.issues,
    changelogUrl: pages.changelog,
    releasesUrl: pages.releases,
    tagsUrl: pages.tags,
  }
}


// GitLab keeps a project's pages under `/-/`, and Bitbucket lists its tags
// among its downloads; any other host is laid out as GitHub is.
function repoPages(host: string, repoUrl: string) {
  if (host.includes('gitlab')) {
    return {
      name: 'GitLab',
      issues: `${repoUrl}/-/issues`,
      changelog: `${repoUrl}/-/blob/main/CHANGELOG.md`,
      releases: `${repoUrl}/-/releases`,
      tags: `${repoUrl}/-/tags`,
    }
  }
  if ('bitbucket.org' === host) {
    return {
      name: 'Bitbucket',
      issues: `${repoUrl}/issues`,
      changelog: `${repoUrl}/src/main/CHANGELOG.md`,
      releases: `${repoUrl}/downloads/?tab=tags`,
      tags: `${repoUrl}/downloads/?tab=tags`,
    }
  }
  return {
    name: host.includes('github') ? 'GitHub' : host,
    issues: `${repoUrl}/issues`,
    changelog: `${repoUrl}/blob/main/CHANGELOG.md`,
    releases: `${repoUrl}/releases`,
    tags: `${repoUrl}/tags`,
  }
}


function docsSiteUrl(model: any): string {
  const { host, path } = repoInfo(model)

  if ('github.com' !== host) {
    return ''
  }

  const editions = kindCollection(model, 'edition')
  // published, not active: serving is per-repository state, not generation.
  const pages: any = Object.values(editions || {})
    .find((e: any) => 'github-pages' === e?.kind && false !== e?.active && true === e?.published)

  if (null == pages) {
    return ''
  }

  const seg = path.split('/')
  const org = seg[0]
  const repo = seg[seg.length - 1]

  return org && repo ? `https://${org}.github.io/${repo}/` : ''
}


function goModule(model: any, target: string): string {
  const declared = model?.main?.[KIT]?.target?.[target]?.module?.path
  if (null != declared && '' !== declared) {
    return String(declared)
  }

  const { host, path } = repoInfo(model)
  return `${host}/${path}/${target}`
}


function packageVersion(model: any, target: string): string {
  const declared = model?.main?.[KIT]?.target?.[target]?.publish?.version
  return null != declared && '' !== declared ? String(declared) : '0.0.1'
}


function goVersion(model: any, target: string, fallback?: string): string {
  const declared = model?.main?.[KIT]?.target?.[target]?.module?.goversion
  if (null != declared && '' !== declared) {
    return String(declared)
  }
  return fallback || '1.21'
}


function goPackageIdent(model: any, target: string): string {
  const declared = model?.main?.[KIT]?.target?.[target]?.module?.package
  if (null != declared && '' !== declared) {
    return String(declared)
  }

  const ident = (s: string) => String(s || '').replace(/[^a-z0-9]/gi, '').toLowerCase()

  const org = ident((model.origin || 'voxgig-sdk').replace(/-sdk$/, ''))
  let slug = ident(model.name)

  if ('' !== org && slug.startsWith(org)) {
    slug = slug.slice(org.length)
  }

  return org + slug + 'sdk'
}


function registryState(model: any, target: string): 'tag' | 'pending' | 'active' | 'inactive' {
  const eco = originName(model, target)
  if ('go' === eco || 'go-cli' === eco || 'go-mcp' === eco) return 'tag'
  const reg = model?.main?.[KIT]?.target?.[target]?.publish?.registry
  if (null == reg || '' === (reg.name || '')) return 'tag'
  if (true === reg.active) return 'active'
  const s = reg.state
  if ('active' === s || 'inactive' === s || 'pending' === s) return s
  return 'pending'
}

// True only when the package is actually live on its registry (so a README
// may print the real `npm install`/`pip install`/... command). Everything
// else — pending, inactive, tag-only — installs from the git tag instead.
function isPublished(model: any, target: string): boolean {
  return 'active' === registryState(model, target)
}

// The registry a target uploads to (npm | pypi | packagist | ...), or ''
// for tag-only ports. Used in the "not yet on <registry>" pending message.
function registryName(model: any, target: string): string {
  const reg = model?.main?.[KIT]?.target?.[target]?.publish?.registry
  return (reg && reg.name) ? String(reg.name) : ''
}

// The vendor / git-tag install pointer for a NOT-yet-published target. For
// go this is the canonical install (`go get <module>@latest`, which the Go
// proxy resolves from the `go/vX.Y.Z` tag); go-cli and go-mcp get ''. For registry
// ports it is a short "not yet on <registry> — install from the git tag"
// pointer carrying the tags URL.
function vendorCommand(model: any, target: string): string {
  const { tagsUrl } = repoInfo(model)
  switch (originName(model, target)) {
    // `target`, not the literal — the case says WHICH command, the argument
    // says whose module. Writing the literal here reintroduces the same bug
    // the switch above exists to fix, one level down, which is exactly what
    // the first cut of this change did.
    case 'go':
      return `go get ${packageName(model, target)}@latest`
    // go-cli and go-mcp reach the SDK through `replace => ../go`, and the Go
    // proxy cannot install a module that needs one. There is no command to
    // give, so the caller links to the target README's build steps.
    case 'go-cli':
    case 'go-mcp':
      return ''
    default: {
      const reg = registryName(model, target)
      return `not yet on ${reg || 'the registry'} — install from the git tag: ${tagsUrl}`
    }
  }
}

function apiName(model: any): string {
  const info = modelText(model)
  const raw = (null != info.title ? String(info.title) : '').trim()
  const stripped = raw.replace(/\s*API\s*$/i, '').trim()
  return stripped || nom(model, 'Name') || model.name
}

function packageName(model: any, eco: string): string {
  const slug = model.name
  const origin = model.origin || 'voxgig-sdk'
  const base = sdkName(slug)
  const npmScoped = `@${origin}/${base}`

  const ECO_TARGET: Record<string, string> = {
    npm: 'ts', pypi: 'py', gem: 'rb', luarocks: 'lua', composer: 'php',
  }
  const declared = model?.main?.[KIT]?.target?.[ECO_TARGET[eco] || eco]
    ?.publish?.registry?.package
  if (null != declared && '' !== declared) {
    return String(declared)
  }

  // The lookup above is keyed by the target's OWN name, so an alias reads its
  // own declared package. The switch below is about FORM — npm scoping,
  // slash-separated composer names — which belongs to the language, so it
  // follows the origin. Passing `ts2` here without this would miss every case
  // and fall to `default`, silently publishing under a non-npm name.
  switch (originName(model, eco)) {
    case 'npm':
    case 'ts':
      return npmScoped
    case 'js':
      return `${npmScoped}-js`
    case 'pypi':
    case 'py':
    case 'gem':
    case 'rb':
    case 'luarocks':
    case 'lua':
      return `${origin}-${base}`
    case 'composer':
    case 'php':
      return `${origin}/${base}`
    // `eco`, not the literal: the case is chosen by the LANGUAGE but the
    // module belongs to the target that asked. `packageName(model, 'go2')`
    // returning go's module was the same conflation one level down.
    case 'go':
    case 'go-cli':
    case 'go-mcp':
      return goModule(model, eco)
    case 'py-data':
      return `${origin}-${base}-data`
    default:
      return `${origin}-${base}`
  }
}


// For any other consumer packageName would answer the SDK's own name.
const NAMED_CONSUMERS = ['go-cli', 'go-mcp', 'py-data']

function hasPackageName(model: any, target: string): boolean {
  const declared = model?.main?.[KIT]?.target?.[target]
  if (!isConsumer(declared)) {
    return true
  }
  const pkg = declared?.publish?.registry?.package
  return (null != pkg && '' !== pkg) || NAMED_CONSUMERS.includes(originName(model, target))
}

// Copy-paste install command for a target, using the REAL package name.
// Only a package that is actually live on its registry (isPublished) gets a
// registry install command; everything else (pending / inactive / tag-only,
// including the whole go family) returns the git-tag vendor command instead,
// so a README never prints a `npm install ...` that 404s.
function installCommand(model: any, target: string): string {
  if (!isPublished(model, target)) {
    return vendorCommand(model, target)
  }
  switch (originName(model, target)) {
    case 'ts':
    case 'js':
      return `npm install ${packageName(model, target)}`
    case 'py':
    case 'py-data':
      return `pip install ${packageName(model, target)}`
    case 'php':
      return `composer require ${packageName(model, target)}`
    case 'rb':
      return `gem install ${packageName(model, target)}`
    case 'lua':
      return `luarocks install ${packageName(model, target)}`
    case 'go':
      return `go get ${packageName(model, target)}`
    default:
      return ''
  }
}

function pkgDescription(model: any, target: string): string {
  return `Unofficial generated ${langLabel(originName(model, target))} SDK` +
    ` for the ${apiName(model)} public API.` +
    ` Not affiliated with or endorsed by the upstream API provider.`
}

// JSON's string escapes are all TOML's; TOML also refuses a raw DEL.
function tomlString(s: string): string {
  return JSON.stringify(String(s)).replace(/\x7f/g, '\\u007F')
}


// Longer non-affiliation / generated-code disclosure for READMEs, LICENSE and
// SECURITY.md. Generic on the upstream owner (owner names are only ~45%
// reliably known across the fleet).
function nonAffiliation(model: any): string {
  return `This is an unofficial SDK for the ${apiName(model)} public API, generated by ` +
    `${publisherInfo(model).name} with [\`@voxgig/sdkgen\`](${GENERATOR_URL}). ` +
    `It is not affiliated with, endorsed by, or sponsored by the upstream API provider.`
}

function keywords(model: any): string[] {
  return [...(isDefaultPublisher(model) ? ['voxgig'] : []),
    'sdk', 'generated-sdk', 'openapi', 'api-client', model.name]
}


function declaredText(value: any): string {
  return null != value && '' !== value ? String(value) : ''
}


// Voxgig's url and security contact apply only while Voxgig is the publisher.
function publisherInfo(model: any): { name: string, url: string, security: string } {
  const declared = model?.main?.[KIT]?.publisher || {}

  const name = declaredText(declared.name) || PUBLISHER
  const own = PUBLISHER === name

  return {
    name,
    url: declaredText(declared.url) || (own ? PUBLISHER_URL : ''),
    security: declaredText(declared.security) || (own ? SECURITY_EMAIL : ''),
  }
}


function isDefaultPublisher(model: any): boolean {
  return PUBLISHER === publisherInfo(model).name
}


// Completes "Please report security issues ...".
function securityContact(model: any): string {
  const { name, url, security } = publisherInfo(model)
  return '' !== security ? `to ${security}` :
    `privately to ${name}` + ('' !== url ? ` (${url})` : '')
}


function authorInfo(model: any, target?: string): { name: string, url: string } {
  const perTarget = null == target ? null :
    model?.main?.[KIT]?.target?.[target]?.author

  const declared = (null != perTarget && '' !== (perTarget.name || '')) ?
    perTarget : (model?.main?.[KIT]?.author || {})

  const publisher = publisherInfo(model)

  const name = declaredText(declared.name) || publisher.name

  const url = declaredText(declared.url) ||
    (publisher.name === name ? publisher.url : '')

  return { name, url }
}


function contributorList(model: any): { name: string, url: string }[] {
  return each(model?.main?.[KIT]?.contributor || {})
    .filter((c: any) => null != c && null != c.name && '' !== c.name)
    .map((c: any) => ({
      name: String(c.name),
      url: null != c.url && '' !== c.url ? String(c.url) : '',
    }))
}

function envToken(name: any): string {
  return String(name || '').toUpperCase().replace(/[^A-Z0-9]+/g, '_').replace(/^_+|_+$/g, '')
}


function envName(model: any): string {
  return envToken(model.name)
}

export {
  sdkName,
  PUBLISHER,
  PUBLISHER_URL,
  SECURITY_EMAIL,
  GENERATOR_URL,
  LANG_LABEL,
  langLabel,
  originName,
  repoInfo,
  apiName,
  packageName,
  hasPackageName,
  installCommand,
  registryState,
  isPublished,
  registryName,
  vendorCommand,
  pkgDescription,
  tomlString,
  nonAffiliation,
  keywords,
  publisherInfo,
  isDefaultPublisher,
  securityContact,
  authorInfo,
  contributorList,
  envName,
  envToken,
  goModule,
  goVersion,
  goPackageIdent,
  packageVersion,
  docsSiteUrl,
}
