from pathlib import Path
import re, json, sys

root = Path(__file__).resolve().parents[1]
required_dirs = ['backend','web-admin','mobile-engineer','database','docker','docs','scripts','shared-types']
required_files = [
    'README_BN.md','README_DEPLOYMENT.md','ENV.example','docker-compose.yml',
    'database/0001_schema_postgres.sql','database/0002_role_permissions.sql',
    'database/0003_enterprise_required_tables.sql','database/0004_push_notification_devices.sql',
    'docs/API_DOCUMENTATION.md','docs/DATABASE_SCHEMA.md','docs/ROLE_PERMISSION_MATRIX.md',
    'docs/DATA_MIGRATION_GUIDE.md','docs/SYNC_ARCHITECTURE.md','docs/MOBILE_BUILD_GUIDE.md',
    'docs/PLAY_CONSOLE_RELEASE_GUIDE.md','docs/TEST_RESULTS.md','docs/BUG_FIX_LOG.md',
    'docs/OPENAPI_MINIMAL.json','docs/FIREBASE_ANDROID_INTEGRATION.md',
    'mobile-engineer/google-services.json'
]
fail=[]
for d in required_dirs:
    if not (root/d).is_dir(): fail.append(f'missing directory: {d}')
for f in required_files:
    if not (root/f).is_file(): fail.append(f'missing file: {f}')

route_file = root/'backend/src/routes/index.ts'
routes = route_file.read_text(encoding='utf-8') if route_file.exists() else ''
for r in ['/auth','/dashboard','/customers','/service-tickets','/stock','/users','/sync','/files','/notifications']:
    if r.strip('/') not in routes: fail.append(f'route group may be missing: {r}')

secret_patterns=[
    r'password\s*=\s*["\'][^<\n]{6,}["\']',
    r'api[_-]?key\s*=\s*["\'][^<\n]{10,}["\']',
    r'sk-[A-Za-z0-9]{20,}'
]
ignored_parts={'node_modules','dist','.git','.expo','android','ios'}
for path in root.rglob('*'):
    if not path.is_file() or any(part in ignored_parts for part in path.parts):
        continue
    # Firebase Android client API key is intentionally stored in google-services.json;
    # it is not a server credential. Service-account JSON remains forbidden by .gitignore.
    if path.name == 'google-services.json':
        continue
    if path.suffix.lower() not in {'.ts','.tsx','.js','.json','.md','.env','.sql','.yml','.yaml'}:
        continue
    txt=path.read_text(errors='ignore')
    for pat in secret_patterns:
        if re.search(pat,txt,re.I):
            fail.append(f'possible hardcoded secret: {path.relative_to(root)}')

if fail:
    print(json.dumps({'ok':False,'issues':fail}, indent=2))
    sys.exit(1)
print(json.dumps({
    'ok':True,
    'required_dirs':required_dirs,
    'required_files':len(required_files),
    'routes_indexed':True,
    'firebase_config_checked_separately':True
}, indent=2))
