import os
import re
root = os.path.abspath(os.path.dirname(__file__))
exclude_dirs = {'__pycache__', '.git', 'node_modules'}
all_files = []
for dirpath, dirnames, filenames in os.walk(root):
    dirnames[:] = [d for d in dirnames if d not in exclude_dirs]
    for fn in filenames:
        p = os.path.join(dirpath, fn)
        if p.endswith(('.pyc', '.sqlite3', '.db')):
            continue
        all_files.append(p)
file_texts = {
    p: open(p, encoding='utf-8', errors='ignore').read()
    for p in all_files
    if os.path.splitext(p)[1] in {'.py', '.html', '.txt', '.md', '.js', '.css'}
}
unused = []
for p in all_files:
    ext = os.path.splitext(p)[1]
    if ext not in {'.py', '.html', '.css', '.js', '.png', '.jpg', '.jpeg', '.webp', '.gif', '.svg', '.txt', '.md'}:
        continue
    norm = p.replace('\\', '/')
    if 'migrations' in norm or '__pycache__' in norm:
        continue
    if os.path.basename(p) == '__init__.py':
        continue
    name = os.path.basename(p)
    found = False
    regex = re.escape(name)
    for qpath, text in file_texts.items():
        if qpath == p:
            continue
        if re.search(regex, text):
            found = True
            break
    if not found:
        unused.append(p)
out = ['TOTAL %s' % len(all_files), 'CANDIDATE_UNUSED %s' % len(unused)]
out.extend(sorted(unused))
with open(os.path.join(root, 'unused-files-report.txt'), 'w', encoding='utf-8') as f:
    f.write('\n'.join(out))
print('Report written:', os.path.join(root, 'unused-files-report.txt'))
