import unittest
import sys
import os
from doclatam.br.cpf import CPF
from doclatam.ar.cuit import CUIT
from doclatam.mx.curp import CURP
from doclatam.br import extract_all
from doclatam.core.result import ValidationResult

class TestNewFeatures(unittest.TestCase):

    def test_metadata_extraction(self):
        # CPF Origin
        # 8 = SP
        # 123.456.788-10 is valid
        self.assertEqual(CPF.get_origin("123.456.788-10"), "SP")
        
        # CUIT Type
        self.assertEqual(CUIT.get_type("20-12345678-9"), "Pessoa Física")
        self.assertEqual(CUIT.get_type("30-12345678-9"), "Empresa")
        
        # CURP Metadata
        curp = CURP.generate()
        meta = CURP.get_metadata(curp)
        self.assertIsNotNone(meta)
        self.assertIn('birth_date', meta)
        self.assertIn('gender', meta)
        self.assertIn('state', meta)

    def test_masking(self):
        doc = "123.456.789-00"
        masked = CPF.mask(doc)
        # Cleaned is 12345678900 (11 chars)
        # Masked should be *******8900
        self.assertEqual(masked, "*******8900")
        
    def test_search_extract(self):
        valid_cpf = CPF.generate()
        
        text = f"Test {valid_cpf} inside text."
        results = extract_all(text)
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0]['type'], 'CPF')
        self.assertEqual(results[0]['value'], valid_cpf)

    def test_granular_errors(self):
        res = CPF.check("123")
        self.assertFalse(res.valid)
        self.assertEqual(res.error_code, "LENGTH_ERROR")
        
        res = CPF.check("111.111.111-11")
        self.assertFalse(res.valid)
        self.assertEqual(res.error_code, "INVALID_DIGITS")
        
        # Checksum error
        # 12345678909 is invalid checksum usually
        res = CPF.check("123.456.789-00") 
        if not res.valid and res.error_code != "INVALID_DIGITS" and res.error_code != "LENGTH_ERROR":
             self.assertEqual(res.error_code, "CHECKSUM_ERROR")

    def test_fuzzy_comparison(self):
        doc1 = "123.456.789-00"
        doc2 = "12345678900"
        self.assertTrue(CPF.compare(doc1, doc2))

    def test_regex_export(self):
        pattern = CPF.get_validation_pattern()
        self.assertEqual(pattern, r"^\d{3}\.\d{3}\.\d{3}-\d{2}$")

    def test_validate_bulk(self):
        docs = [CPF.generate(), "123", CPF.generate()]
        results = CPF.validate_bulk(docs)
        self.assertEqual(results, [True, False, True])

if __name__ == '__main__':
    unittest.main()
