{-# LANGUAGE OverloadedStrings #-}

-- | High-level API for Internationalized Domain Names (IDN) processing.
--
-- This module provides functions for converting between Unicode and ASCII
-- domain names, following the IDNA2008 specification (RFC 5890-5893).
--
-- == Overview
--
-- Internationalized Domain Names allow domain names to contain non-ASCII
-- characters. This library implements IDNA2008, which uses Punycode encoding
-- to represent Unicode characters in ASCII-compatible form.
--
-- == Example
--
-- >>> toASCII "münchen.de"
-- Right "xn--mnchen-3ya.de"
--
-- >>> toUnicode "xn--mnchen-3ya.de"
-- Right "münchen.de"
--
-- >>> validateLabel "example"
-- Right ()
--
-- == See Also
--
-- * 'Data.Text.Punycode' for low-level Punycode encoding/decoding
-- * RFC 5890-5893 for the full IDNA2008 specification
module Data.Text.IDN
  ( -- * Main API
    toASCII
  , toUnicode
  , validateLabel
  
    -- * Types
  , module Data.Text.IDN.Types
  ) where

import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.IDN.Types
import Data.Text.IDN.Internal.Unicode
import Data.Text.IDN.Internal.Validation
import Data.Text.IDN.Internal.Punycode (encodePunycode, decodePunycode)
import Data.List.NonEmpty (NonEmpty)
import qualified Data.List.NonEmpty as NE
import Data.Char (ord, isAscii)

-- | Convert a Unicode domain name to ASCII (A-label) form per RFC 5891.
--
-- Converts each label in the domain name to its ASCII-compatible form.
-- Unicode labels are encoded using Punycode and prefixed with "xn--".
-- ASCII labels are normalized to lowercase (case-insensitive per DNS).
--
-- === Examples
--
-- >>> toASCII "münchen.de"
-- Right "xn--mnchen-3ya.de"
--
-- >>> toASCII "EXAMPLE.COM"
-- Right "example.com"
--
-- === Errors
--
-- Returns 'Left' with 'IDNError' if:
-- * Any label is empty or too long
-- * Any label contains disallowed code points
-- * Bidirectional text rules are violated
-- * Contextual validation fails
--
-- @since 0.1.0.0
toASCII :: Text -> Either IDNError Text
toASCII :: Text -> Either IDNError Text
toASCII Text
input = do
  DomainName
domain <- Text -> Either IDNError DomainName
mkDomainName Text
input
  NonEmpty Label
processedLabels <- (Label -> Either IDNError Label)
-> NonEmpty Label -> Either IDNError (NonEmpty Label)
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> NonEmpty a -> f (NonEmpty b)
traverse Label -> Either IDNError Label
processLabelToASCII (DomainName -> NonEmpty Label
labels DomainName
domain)
  Text -> Either IDNError Text
forall a. a -> Either IDNError a
forall (m :: * -> *) a. Monad m => a -> m a
return (Text -> Either IDNError Text) -> Text -> Either IDNError Text
forall a b. (a -> b) -> a -> b
$ Text -> [Text] -> Text
T.intercalate Text
"." ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ (Label -> Text) -> [Label] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Label -> Text
labelText (NonEmpty Label -> [Label]
forall a. NonEmpty a -> [a]
NE.toList NonEmpty Label
processedLabels)
  where
    labelText :: Label -> Text
labelText (ULabel Text
t) = Text
t
    labelText (ALabel Text
t) = Text
t

-- | Convert an ASCII domain name to Unicode (U-label) form per RFC 5891.
--
-- Converts each label in the domain name to its Unicode form.
-- Punycode-encoded labels (starting with "xn--") are decoded to Unicode.
-- Pure ASCII labels are validated and passed through unchanged.
--
-- === Examples
--
-- >>> toUnicode "xn--mnchen-3ya.de"
-- Right "münchen.de"
--
-- >>> toUnicode "example.com"
-- Right "example.com"
--
-- === Errors
--
-- Returns 'Left' with 'IDNError' if:
-- * Any label is empty or too long
-- * Punycode decoding fails
-- * Any label contains disallowed code points
-- * Bidirectional text rules are violated
--
-- @since 0.1.0.0
toUnicode :: Text -> Either IDNError Text
toUnicode :: Text -> Either IDNError Text
toUnicode Text
input = do
  DomainName
domain <- Text -> Either IDNError DomainName
mkDomainName Text
input
  NonEmpty Label
processedLabels <- (Label -> Either IDNError Label)
-> NonEmpty Label -> Either IDNError (NonEmpty Label)
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> NonEmpty a -> f (NonEmpty b)
traverse Label -> Either IDNError Label
processLabelToUnicode (DomainName -> NonEmpty Label
labels DomainName
domain)
  Text -> Either IDNError Text
forall a. a -> Either IDNError a
forall (m :: * -> *) a. Monad m => a -> m a
return (Text -> Either IDNError Text) -> Text -> Either IDNError Text
forall a b. (a -> b) -> a -> b
$ Text -> [Text] -> Text
T.intercalate Text
"." ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ (Label -> Text) -> [Label] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Label -> Text
labelText (NonEmpty Label -> [Label]
forall a. NonEmpty a -> [a]
NE.toList NonEmpty Label
processedLabels)
  where
    labelText :: Label -> Text
labelText (ULabel Text
t) = Text
t
    labelText (ALabel Text
t) = Text
t

-- | Process a single label to ASCII form.
processLabelToASCII :: Label -> Either IDNError Label
processLabelToASCII :: Label -> Either IDNError Label
processLabelToASCII (ALabel Text
t)
  -- Labels are already normalized to lowercase by mkLabel
  | Text
"xn--" Text -> Text -> Bool
`T.isPrefixOf` Text
t = do
      -- It's a Punycode A-label, validate it by decoding and re-encoding
      -- This uses processLabelToUnicode which validates Punycode properly
      Label
ulabel <- Label -> Either IDNError Label
processLabelToUnicode (Text -> Label
ALabel Text
t)
      -- Then re-process back to ASCII to get a validated A-label
      Label -> Either IDNError Label
processLabelToASCII Label
ulabel
  | Bool
otherwise =
      -- Regular ASCII label (already normalized), just validate
      Text -> Either IDNError ()
validateLabel Text
t Either IDNError ()
-> Either IDNError Label -> Either IDNError Label
forall a b.
Either IDNError a -> Either IDNError b -> Either IDNError b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Label -> Either IDNError Label
forall a. a -> Either IDNError a
forall (m :: * -> *) a. Monad m => a -> m a
return (Text -> Label
ALabel Text
t)

processLabelToASCII (ULabel Text
t)
  | Text -> Bool
isAsciiLabel Text
t = do
      -- Pure ASCII label (already normalized), just validate
      Text -> Either IDNError ()
validateLabel Text
t
      Label -> Either IDNError Label
forall a. a -> Either IDNError a
forall (m :: * -> *) a. Monad m => a -> m a
return (Text -> Label
ULabel Text
t)
  
  | Bool
otherwise = do
      -- Unicode label, needs Punycode encoding
      Text -> Either IDNError ()
validateLabel Text
t
      Text
encoded <- case Text -> Either PunycodeError Text
encodePunycode Text
t of
        Left PunycodeError
err -> IDNError -> Either IDNError Text
forall a b. a -> Either a b
Left (Text -> Text -> IDNError
PunycodeDecodeError Text
t (String -> Text
T.pack (PunycodeError -> String
forall a. Show a => a -> String
show PunycodeError
err)))
        Right Text
e -> Text -> Either IDNError Text
forall a b. b -> Either a b
Right Text
e
      let aLabel :: Text
aLabel = Text
"xn--" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
encoded
      
      -- Validate length constraints
      if Text -> Int
T.length Text
aLabel Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
63
        then IDNError -> Either IDNError Label
forall a b. a -> Either a b
Left (Int -> Int -> IDNError
LabelTooLong (Text -> Int
T.length Text
aLabel) Int
63)
        else Label -> Either IDNError Label
forall a. a -> Either IDNError a
forall (m :: * -> *) a. Monad m => a -> m a
return (Text -> Label
ALabel Text
aLabel)

-- | Process a single label to Unicode form.
processLabelToUnicode :: Label -> Either IDNError Label
processLabelToUnicode :: Label -> Either IDNError Label
processLabelToUnicode (ULabel Text
t) =
  -- Already Unicode, validate and return
  Text -> Either IDNError ()
validateLabel Text
t Either IDNError ()
-> Either IDNError Label -> Either IDNError Label
forall a b.
Either IDNError a -> Either IDNError b -> Either IDNError b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Label -> Either IDNError Label
forall a. a -> Either IDNError a
forall (m :: * -> *) a. Monad m => a -> m a
return (Text -> Label
ULabel Text
t)

processLabelToUnicode (ALabel Text
t)
  -- RFC 5891 Section 5.1: A-labels are case-insensitive for matching
  | Text
"xn--" Text -> Text -> Bool
`T.isPrefixOf` Text -> Text
T.toLower Text
t = do
      -- Punycode A-label, decode it
      -- RFC 5891 Section 5.1: Accept case-insensitive input, normalize to lowercase
      -- Drop the prefix (which might be XN--, Xn--, xN--, or xn--)
      let encoded :: Text
encoded = Int -> Text -> Text
T.drop Int
4 Text
t
          encodedLower :: Text
encodedLower = Text -> Text
T.toLower Text
encoded

      Text
decoded <- case Text -> Either PunycodeError Text
decodePunycode Text
encodedLower of
        Left PunycodeError
err -> IDNError -> Either IDNError Text
forall a b. a -> Either a b
Left (Text -> Text -> IDNError
PunycodeDecodeError Text
encoded (String -> Text
T.pack (PunycodeError -> String
forall a. Show a => a -> String
show PunycodeError
err)))
        Right Text
d -> Text -> Either IDNError Text
forall a b. b -> Either a b
Right Text
d

      -- Punycode-encoded labels must contain at least one non-ASCII character
      -- If the decoded result is pure ASCII, it shouldn't have been encoded
      if Text -> Bool
isAsciiLabel Text
decoded
        then IDNError -> Either IDNError ()
forall a b. a -> Either a b
Left (Text -> Text -> IDNError
PunycodeDecodeError Text
encoded Text
"Punycode used for pure ASCII label")
        else () -> Either IDNError ()
forall a. a -> Either IDNError a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()

      -- RFC 5891 Section 4.4: Verify round-trip consistency
      -- Re-encode and check it matches the lowercase normalized form
      Text
reencoded <- case Text -> Either PunycodeError Text
encodePunycode Text
decoded of
        Left PunycodeError
err -> IDNError -> Either IDNError Text
forall a b. a -> Either a b
Left (Text -> Text -> IDNError
PunycodeDecodeError Text
decoded (String -> Text
T.pack (PunycodeError -> String
forall a. Show a => a -> String
show PunycodeError
err)))
        Right Text
e -> Text -> Either IDNError Text
forall a b. b -> Either a b
Right Text
e
      if Text
reencoded Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
/= Text
encodedLower
        then IDNError -> Either IDNError Label
forall a b. a -> Either a b
Left (Text -> Text -> IDNError
PunycodeDecodeError Text
encoded Text
"Round-trip re-encoding failed")
        else do
          Text -> Either IDNError ()
validateLabel Text
decoded
          Label -> Either IDNError Label
forall a. a -> Either IDNError a
forall (m :: * -> *) a. Monad m => a -> m a
return (Text -> Label
ULabel Text
decoded)

  | Bool
otherwise =
      -- Pure ASCII label, validate and return
      Text -> Either IDNError ()
validateLabel Text
t Either IDNError ()
-> Either IDNError Label -> Either IDNError Label
forall a b.
Either IDNError a -> Either IDNError b -> Either IDNError b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Label -> Either IDNError Label
forall a. a -> Either IDNError a
forall (m :: * -> *) a. Monad m => a -> m a
return (Text -> Label
ALabel Text
t)

-- | Validate a single domain label per IDNA2008 rules.
--
-- Performs comprehensive validation including:
-- * Length constraints (max 63 characters)
-- * Hyphen position rules
-- * Code point validity (PVALID, CONTEXTJ, CONTEXTO)
-- * Contextual rule validation
-- * Bidirectional text rules (RFC 5893)
--
-- === Examples
--
-- >>> validateLabel "example"
-- Right ()
--
-- >>> validateLabel ""
-- Left EmptyLabel
--
-- === Errors
--
-- Returns 'Left' with 'IDNError' if validation fails. See 'IDNError'
-- constructors for specific error types.
--
-- @since 0.1.0.0
validateLabel :: Text -> Either IDNError ()
validateLabel :: Text -> Either IDNError ()
validateLabel Text
label = do
  -- Check empty
  if Text -> Bool
T.null Text
label
    then IDNError -> Either IDNError ()
forall a b. a -> Either a b
Left IDNError
EmptyLabel
    else () -> Either IDNError ()
forall a. a -> Either IDNError a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
  
  -- Check length (before encoding)
  if Text -> Int
T.length Text
label Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
63
    then IDNError -> Either IDNError ()
forall a b. a -> Either a b
Left (Int -> Int -> IDNError
LabelTooLong (Text -> Int
T.length Text
label) Int
63)
    else () -> Either IDNError ()
forall a. a -> Either IDNError a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
  
  -- Check hyphen positions
  Text -> Either IDNError ()
checkHyphens Text
label
  
  -- Check combining marks at start
  case Text -> Maybe (Char, Text)
T.uncons Text
label of
    Just (Char
c, Text
_) | Char -> Bool
isCombiningMark Char
c ->
      IDNError -> Either IDNError ()
forall a b. a -> Either a b
Left (Char -> Int -> IDNError
StartsWithCombiningMark Char
c (Char -> Int
ord Char
c))
    Maybe (Char, Text)
_ -> () -> Either IDNError ()
forall a. a -> Either IDNError a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
  
  -- Validate each code point
  (Char -> Either IDNError ()) -> String -> Either IDNError ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ Char -> Either IDNError ()
validateCodePoint (Text -> String
T.unpack Text
label)
  
  -- Validate contextual rules for CONTEXTJ/CONTEXTO
  Text -> Either IDNError ()
validateContextualRules Text
label
  
  -- Validate bidi rules
  Text -> Either IDNError ()
validateBidiRules Text
label
  
  () -> Either IDNError ()
forall a. a -> Either IDNError a
forall (m :: * -> *) a. Monad m => a -> m a
return ()

-- | Check hyphen position rules.
checkHyphens :: Text -> Either IDNError ()
checkHyphens :: Text -> Either IDNError ()
checkHyphens Text
label = do
  case Text -> Maybe (Char, Text)
T.uncons Text
label of
    Just (Char
'-', Text
_) -> IDNError -> Either IDNError ()
forall a b. a -> Either a b
Left (HyphenError -> IDNError
InvalidHyphenPosition HyphenError
StartsWithHyphen)
    Maybe (Char, Text)
_ -> () -> Either IDNError ()
forall a. a -> Either IDNError a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()

  case Text -> Maybe (Text, Char)
T.unsnoc Text
label of
    Just (Text
_, Char
'-') -> IDNError -> Either IDNError ()
forall a b. a -> Either a b
Left (HyphenError -> IDNError
InvalidHyphenPosition HyphenError
EndsWithHyphen)
    Maybe (Text, Char)
_ -> () -> Either IDNError ()
forall a. a -> Either IDNError a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()

  -- Check for "--" in positions 3-4 (unless it's an A-label with xn--)
  -- RFC 5891: A-labels are case-insensitive for matching
  let labelLower :: Text
labelLower = Text -> Text
T.toLower Text
label
  if Text -> Int
T.length Text
label Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
4 Bool -> Bool -> Bool
&& Bool -> Bool
not (Text
"xn--" Text -> Text -> Bool
`T.isPrefixOf` Text
labelLower)
    then if HasCallStack => Text -> Int -> Char
Text -> Int -> Char
T.index Text
label Int
2 Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'-' Bool -> Bool -> Bool
&& HasCallStack => Text -> Int -> Char
Text -> Int -> Char
T.index Text
label Int
3 Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'-'
      then IDNError -> Either IDNError ()
forall a b. a -> Either a b
Left (HyphenError -> IDNError
InvalidHyphenPosition HyphenError
HyphensAt3And4NotPunycode)
      else () -> Either IDNError ()
forall a. a -> Either IDNError a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
    else () -> Either IDNError ()
forall a. a -> Either IDNError a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()

-- | Validate a single code point.
validateCodePoint :: Char -> Either IDNError ()
validateCodePoint :: Char -> Either IDNError ()
validateCodePoint Char
c =
  case Char -> CodePointStatus
codePointStatus Char
c of
    CodePointStatus
PVALID -> () -> Either IDNError ()
forall a. a -> Either IDNError a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
    CodePointStatus
DISALLOWED -> IDNError -> Either IDNError ()
forall a b. a -> Either a b
Left (Char -> Int -> IDNError
DisallowedCodePoint Char
c (Char -> Int
ord Char
c))
    CodePointStatus
CONTEXTJ -> () -> Either IDNError ()
forall a. a -> Either IDNError a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()  -- Will be checked in context validation
    CodePointStatus
CONTEXTO -> () -> Either IDNError ()
forall a. a -> Either IDNError a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()  -- Will be checked in context validation
    CodePointStatus
UNASSIGNED -> IDNError -> Either IDNError ()
forall a b. a -> Either a b
Left (Char -> Int -> IDNError
DisallowedCodePoint Char
c (Char -> Int
ord Char
c))

-- | Check if a label is pure ASCII.
isAsciiLabel :: Text -> Bool
isAsciiLabel :: Text -> Bool
isAsciiLabel = (Char -> Bool) -> Text -> Bool
T.all Char -> Bool
isAscii