#!/usr/bin/env python3
"""FIGHTSKILL — Full integration test suite for the enhanced build.

Tests:
  1. Every GET route renders without server errors
  2. Landing page structure (sections, canvases, scripts, CSS)
  3. Div balance on all major pages (HTML integrity)
  4. Auth flow (login → dashboard, signup page)
  5. Static assets exist and are served (JS/CSS/vendor)
  6. Language variants render (fa/tr/ar incl. RTL)
  7. Admin pages render (with admin session)
"""
import re
import sys

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

from app import create_app  # noqa: E402

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

PASS = 0
FAIL = 0
FAILURES = []


def check(name, cond, detail=''):
    global PASS, FAIL
    if cond:
        PASS += 1
        print(f"  ✓ {name}")
    else:
        FAIL += 1
        FAILURES.append(f"{name} {detail}")
        print(f"  ✗ {name} {detail}")


print("=" * 62)
print("FIGHTSKILL ENHANCED BUILD — INTEGRATION TESTS")
print("=" * 62)

# ── 1. All GET routes ────────────────────────────────────────────
print("\n[1] Route scan (all GET endpoints)")
routes = [r.rule for r in app.url_map.iter_rules()
          if 'GET' in r.methods and '<' not in r.rule]
server_errors = 0
for url in sorted(routes):
    try:
        resp = c.get(url, follow_redirects=False)
        if resp.status_code >= 500:
            print(f"  ✗ SERVER ERROR {url} -> {resp.status_code}")
            server_errors += 1
    except Exception as e:
        print(f"  ✗ EXCEPTION {url}: {e}")
        server_errors += 1
check(f"{len(routes)} GET routes, 0 server errors", server_errors == 0)

# ── 2. Landing page structure ────────────────────────────────────
print("\n[2] Landing page structure")
with c.session_transaction() as s:
    s['lang'] = 'en'
    s['region'] = 'global'
r = c.get('/landing')
html = r.get_data(as_text=True)
check('GET /landing = 200', r.status_code == 200)

for marker in ['hero3d-canvas', 'lp-hero-aurora', 'lp-hero-grid-floor',
               'fx-shard-1', 'fx-shard-4', 'particle-net', 'ticker-wrap',
               'stat-band', 'fx-divider', 'fx-feature-strip', 'fx-chip',
               'css/fx3d.css', 'js/hero3d.js', 'js/fx3d.js',
               'js/particle-net.js', 'js/vendor/three.min.js',
               'js/grainient.js', 'js/landing.js', 'js/app.js',
               'grainient-bg', 'bg-orbs', 'scanline',
               'id="tournaments"', 'id="games"', 'id="how-it-works"',
               'id="why"', 'id="leaderboard-cta"', 'lp-footer']:
    check(f'landing contains {marker}', marker in html)

opens = len(re.findall(r'<div\b', html))
closes = len(re.findall(r'</div>', html))
check(f'div balance ({opens}/{closes})', opens == closes)

so = len(re.findall(r'<section\b', html))
sc = len(re.findall(r'</section>', html))
check(f'section balance ({so}/{sc})', so == sc)

# ── 3. Auth pages ────────────────────────────────────────────────
print("\n[3] Auth pages integrity")
for url in ['/auth/login', '/auth/signup', '/auth/forgot']:
    rr = c.get(url)
    hh = rr.get_data(as_text=True)
    o = len(re.findall(r'<div\b', hh))
    cl = len(re.findall(r'</div>', hh))
    check(f'{url} 200 + balanced', rr.status_code == 200 and o == cl,
          f'(status={rr.status_code}, div={o}/{cl})')
    check(f'{url} has fx-tilt card', 'fx-tilt' in hh)

# ── 4. Login flow ────────────────────────────────────────────────
print("\n[4] Auth flow (admin login)")
r = c.post('/auth/login', data={
    'email': 'admin@vapolyx.gg',
    'password': 'Admin@123'
}, follow_redirects=True)
logged_in = r.status_code == 200
check('admin login → 200', logged_in, f'(got {r.status_code})')

if logged_in:
    r2 = c.get('/')
    if r2.status_code == 200:
        pass  # language select — fine
    r3 = c.get('/landing')
    check('landing still renders logged-in', r3.status_code == 200)

# ── 5. Webapp pages with fx3d ───────────────────────────────────
print("\n[5] Webapp pages (logged-in)")
if logged_in:
    for url in ['/home', '/tournaments', '/leaderboard', '/rewards',
                '/wallet', '/profile', '/team', '/search', '/special',
                '/notifications', '/how-it-works', '/support']:
        rr = c.get(url, follow_redirects=False)
        if rr.status_code in (200, 302):
            print(f"  ✓ {url} -> {rr.status_code}")
        else:
            print(f"  ✗ {url} -> {rr.status_code}")
            FAILURES.append(f"{url} -> {rr.status_code}")
            FAIL += 1
        if rr.status_code == 200:
            hh = rr.get_data(as_text=True)
            o = len(re.findall(r'<div\b', hh))
            cl = len(re.findall(r'</div>', hh))
            if o != cl:
                print(f"    ⚠ div mismatch {o}/{cl}")

    # base template should include fx3d
    rr = c.get('/home')
    hh = rr.get_data(as_text=True)
    check('webapp base includes fx3d.css', 'css/fx3d.css' in hh)
    check('webapp base includes fx3d.js', 'js/fx3d.js' in hh)
    check('webapp base includes particle-net', 'particle-net' in hh)

# ── 6. Multi-language rendering ──────────────────────────────────
print("\n[6] Multi-language landing render")
for lang in ['en', 'fa', 'tr', 'ar']:
    with c.session_transaction() as s2:
        s2['lang'] = lang
        s2['region'] = 'global'
    rr = c.get('/landing')
    hh = rr.get_data(as_text=True)
    ok = rr.status_code == 200
    check(f'landing renders in [{lang}]', ok, f'({rr.status_code})')
    if lang in ('fa', 'ar'):
        check(f'[{lang}] RTL enabled', 'dir="rtl"' in hh)

# restore en
with c.session_transaction() as s2:
    s2['lang'] = 'en'

# ── 7. Admin pages ───────────────────────────────────────────────
print("\n[7] Admin pages (admin session)")
if logged_in:
    for url in ['/admin/', '/admin/users', '/admin/games',
                '/admin/matches', '/admin/wallets', '/admin/settings',
                '/admin/transactions']:
        rr = c.get(url, follow_redirects=False)
        status_ok = rr.status_code in (200, 302)
        print(f"  {'✓' if status_ok else '✗'} {url} -> {rr.status_code}")
        if not status_ok:
            FAILURES.append(f"{url} -> {rr.status_code}")
            FAIL += 1

# ── 8. Static assets served ─────────────────────────────────────
print("\n[8] Static assets served")
for asset in ['/static/css/fx3d.css', '/static/js/hero3d.js',
              '/static/js/fx3d.js', '/static/js/particle-net.js',
              '/static/js/vendor/three.min.js', '/static/css/landing.css',
              '/static/css/design.css']:
    rr = c.get(asset)
    check(f'{asset} -> 200 ({rr.content_length or "?"}b)',
          rr.status_code == 200)

# ── Summary ──────────────────────────────────────────────────────
print("\n" + "=" * 62)
print(f"RESULT: {PASS} passed, {FAIL} failed")
if FAILURES:
    print("\nFailures:")
    for f in FAILURES:
        print(f"  - {f}")
print("=" * 62)
sys.exit(1 if FAIL else 0)
