import sys
from pathlib import Path
from pdfminer.high_level import extract_text
import re
from docx import Document
import xlrd
import openpyxl

# ----------------------
# T.C. Kimlik No doğrulama
# ----------------------
def is_valid_tckn(tckn: str) -> bool:
    if len(tckn) != 11 or not tckn.isdigit():
        return False
    d = [int(x) for x in tckn]
    if d[0] == 0:
        return False
    d10_calc = ((d[0] + d[2] + d[4] + d[6] + d[8]) * 7 - (d[1] + d[3] + d[5] + d[7])) % 10
    if d[9] != d10_calc:
        return False
    d11_calc = sum(d[:10]) % 10
    if d[10] != d11_calc:
        return False
    return True

TCKN_PATTERN = re.compile(r'(?<!\d)([1-9](?:\d[ .-]?){9}\d)(?!\d)')

def extract_tckn_from_text(text: str):
    found = set()
    for m in TCKN_PATTERN.finditer(text):
        digits = re.sub(r'\D', '', m.group(1))
        if is_valid_tckn(digits):
            found.add(digits)
    return found

# ----------------------
# PDF okuma
# ----------------------
def scan_pdf(path: Path):
    try:
        text = extract_text(str(path)) or ""
    except Exception:
        return set()
    return extract_tckn_from_text(text)

# ----------------------
# DOCX okuma
# ----------------------
def scan_docx(path: Path):
    try:
        doc = Document(str(path))
        text = "\n".join(p.text for p in doc.paragraphs)
    except Exception:
        return set()
    return extract_tckn_from_text(text)

# ----------------------
# DOC (eski Word) okuma
# ----------------------
def scan_doc(path: Path):
    # doc dosyaları binary olduğu için burada basitçe text ayıklamaya çalışıyoruz
    # daha gelişmiş için textract vb. kullanılabilir
    try:
        with open(path, "rb") as f:
            raw = f.read()
        text = raw.decode(errors="ignore")
    except Exception:
        return set()
    return extract_tckn_from_text(text)

# ----------------------
# XLSX okuma
# ----------------------
def scan_xlsx(path: Path):
    try:
        wb = openpyxl.load_workbook(path, data_only=True)
    except Exception:
        return set()
    text_parts = []
    for sheet in wb.sheetnames:
        ws = wb[sheet]
        for row in ws.iter_rows(values_only=True):
            for cell in row:
                if cell is not None:
                    text_parts.append(str(cell))
    text = "\n".join(text_parts)
    return extract_tckn_from_text(text)

# ----------------------
# XLS okuma
# ----------------------
def scan_xls(path: Path):
    try:
        wb = xlrd.open_workbook(str(path))
    except Exception:
        return set()
    text_parts = []
    for sheet in wb.sheets():
        for r in range(sheet.nrows):
            for c in range(sheet.ncols):
                val = sheet.cell_value(r, c)
                if val != "":
                    text_parts.append(str(val))
    text = "\n".join(text_parts)
    return extract_tckn_from_text(text)

# ----------------------
# Ana tarama
# ----------------------
def main():
    if len(sys.argv) > 1:
        root = Path(sys.argv[1])
    else:
        root = Path.cwd()

    if not root.exists() or not root.is_dir():
        print(f"Hata: {root} klasörü bulunamadı veya klasör değil.")
        sys.exit(1)

    extensions = {".pdf": scan_pdf, ".docx": scan_docx, ".doc": scan_doc,
                  ".xlsx": scan_xlsx, ".xls": scan_xls}

    files_with_tckn = []

    for file_path in root.rglob("*"):
        if file_path.suffix.lower() in extensions:
            tckns = extensions[file_path.suffix.lower()](file_path)
            if tckns:
                files_with_tckn.append((file_path, tckns))
                print(f"[TCKN BULUNDU] {file_path}")

    print("\nÖZET:")
    if not files_with_tckn:
        print("Hiçbir dosyada TCKN bulunamadı.")
    else:
        print(f"{len(files_with_tckn)} dosyada TCKN bulundu:")
        for f, t in files_with_tckn:
            print(f" - {f.name}")

if __name__ == "__main__":
    main()
