import sc from "./lang-sc.json" assert { type: "json" }
import shin from "./lang-shin.json" assert { type: "json" }
import type { Rule } from "~/shared/models"
import { RuleType } from "~/shared/models/enums.generated"

const AZ = /^[A-Za-zÀ-ÖØ-öø-ÿ\d ]+$/

// Handles Han unification font problems
export function guessFileLanguage({ name, rules }: { name: string; rules: Rule[] }) {
  const chars = name.split("")

  // Fast path
  if (AZ.test(name)) {
    return
  }

  // Check if the name contains Japanese kana characters
  if (
    /\p{Script_Extensions=Kana}/u.test(name) ||
    /\p{Script_Extensions=Hira}/u.test(name) ||
    chars.some(c => shin.includes(c))
  ) {
    return "ja"
  }

  // Check if the name contains Korean hangul
  if (/\p{Script_Extensions=Hang}/u.test(name)) {
    return "ko"
  }

  // Check if the name contains Simplified Chinese characters
  if (chars.some(c => sc.includes(c))) {
    return "zh-CN"
  }

  const domains = rules
    .map(r => {
      try {
        return r.type === RuleType.Domain
          ? r.value
          : r.type === RuleType.URL
          ? new URL(r.value).hostname
          : r.type === RuleType.URLPrefix
          ? new URL(r.value).hostname
          : null
      } catch {
        return null
      }
    })
    .filter(Boolean)

  // Check the domains for TLDs that correspond to a specific language
  for (const domain of domains) {
    if (domain.endsWith(".cn")) {
      return "zh-CN"
    }
    if (domain.endsWith(".hk")) {
      return "zh-HK"
    }
    if (domain.endsWith(".tw")) {
      return "zh-TW"
    }
    if (domain.endsWith(".jp")) {
      return "ja"
    }
  }

  if (/\p{Script_Extensions=Hani}/u.test(name)) {
    return "zh-TW"
  }
}
