#!/usr/bin/env python3
"""Deep HTML integrity scan — renders every reachable page (incl. detail
pages with IDs) and verifies HTML div balance (script/style blocks stripped)."""
import re
import sys

sys.path.insert(0, '/home/z/my-project/fightskill')

from app import create_app
from app.extensions import db
from sqlalchemy import text

app = create_app('development')
app.config['TESTING'] = True
c = app.test_client()

# login as admin
c.post('/auth/login', data={'email': 'admin@vapolyx.gg', 'password': 'Admin@123'})

# collect real object ids from DB
game_ids, match_ids = [], []
with app.app_context():
    try:
        rows = db.session.execute(text("SELECT id FROM game LIMIT 5")).fetchall()
        game_ids = [r[0] for r in rows]
    except Exception:
        pass
    try:
        rows = db.session.execute(text("SELECT id FROM match LIMIT 5")).fetchall()
        match_ids = [r[0] for r in rows]
    except Exception:
        pass

urls = ['/', '/landing', '/auth/login', '/auth/signup', '/auth/forgot',
        '/home', '/tournaments', '/leaderboard', '/rewards', '/wallet',
        '/profile', '/team', '/search', '/special', '/notifications',
        '/how-it-works', '/support', '/admin/', '/admin/users',
        '/admin/games', '/admin/matches', '/admin/wallets',
        '/admin/settings', '/admin/transactions', '/admin/social',
        '/admin/support']
for gid in game_ids:
    urls.append(f'/game/{gid}')
    urls.append(f'/admin/games/{gid}/modes')
for mid in match_ids:
    urls.append(f'/tournaments/{mid}')
    urls.append(f'/admin/matches/{mid}/edit')

# fetch game slugs for game detail
with app.app_context():
    try:
        rows = db.session.execute(text("SELECT slug FROM game LIMIT 5")).fetchall()
        for r in rows:
            urls.append(f'/games/{r[0]}')
    except Exception:
        pass

bad = 0
total = 0
for url in urls:
    try:
        r = c.get(url, follow_redirects=True)
    except Exception as e:
        print(f'✗ {url} EXCEPTION {type(e).__name__}: {str(e)[:80]}')
        bad += 1
        total += 1
        continue
    total += 1
    if r.status_code >= 500:
        print(f'✗ {url} -> {r.status_code}')
        bad += 1
        continue
    html = r.get_data(as_text=True)
    clean = re.sub(r'<script\b.*?</script>', '', html, flags=re.S)
    clean = re.sub(r'<style\b.*?</style>', '', clean, flags=re.S)
    # also strip comments to avoid commented-out tags skewing counts
    clean = re.sub(r'<!--.*?-->', '', clean, flags=re.S)
    o = len(re.findall(r'<div\b', clean))
    cl = len(re.findall(r'</div>', clean))
    so = len(re.findall(r'<section\b', clean))
    sc = len(re.findall(r'</section>', clean))
    if o != cl or so != sc:
        print(f'⚠ {url} -> {r.status_code} | div {o}/{cl} | section {so}/{sc}')
        bad += 1

print(f'\nScanned {total} URLs — {bad} with issues')
sys.exit(1 if bad else 0)
