#!/usr/bin/env python3
from pathlib import Path
import re
import sys

if len(sys.argv) != 10:
    raise SystemExit('usage: patch_server_v249387.py relay routes375 routes380 routes382 routes383 routes384 routes385 routes386 routes387')
server = Path(sys.argv[1])
route_files = [Path(value) for value in sys.argv[2:]]
source = server.read_text(encoding='utf-8', errors='strict')
markers = (
    'V249374_PRO_COMMUNITY_LEXICON_ROUTES',
    'V249375_FULL_EXPERIENCE_ROUTES',
    'V249380_MEMBER_COMMUNICATION_GUARD_ROUTES',
    'V249382_UNIFIED_ACCOUNT_SECURITY_ROUTES',
    'V249383_PROFESSIONAL_CENTER_ANALYTICS_LIVE_WALL_ROUTES',
    'V249384_PROFESSIONAL_ACTIVATION_BACKUP_FEED_CLEAN_ROUTES',
    'V249385_STABLE_PROFESSIONAL_GLOBAL_FRIEND_GATE_ROUTES',
    'V249386_PRO_CODE_CONFIRMATION_GLOBAL_FRIEND_CONTINUATION_ROUTES',
    'V249387_CREATOR_PUBLIC_LINK_PUBLICATION_WORKSPACE_ROUTES',
)
for marker in markers:
    source = re.sub(
        r'\n?# BEGIN ' + re.escape(marker) + r'[\s\S]*?# END ' + re.escape(marker) + r'\n?',
        '\n',
        source,
    )
source = re.sub(r'\n?# BEGIN V249383_V411_INSTALL[\s\S]*?# END V249383_V411_INSTALL\n?', '\n', source)
source = re.sub(r'\n?# ===== OK ITHAKI V411 LIVE WALL REACTIONS START =====[\s\S]*?# ===== OK ITHAKI V411 LIVE WALL REACTIONS END =====\n?', '\n', source)
version = '2.4.9.387-creator-public-link-publication-workspace'
source, count = re.subn(
    r'(?m)^VERSION\s*=\s*["\'][^"\']*["\']\s*$',
    f'VERSION  = "{version}"',
    source,
    count=1,
)
if count != 1:
    raise SystemExit('ERROR: VERSION assignment')
helper_pattern = r'def _creator_active_v249405\(room_id: str, device_id: str\) -> bool:\n[\s\S]*?\n\n_V405_VIDEO_HINT_RE'
helper_replacement = '''def _creator_active_v249405(room_id: str, device_id: str) -> bool:
    try:
        row = one("SELECT account_type FROM creator_accounts_v249401 WHERE room_id=? AND device_id=? LIMIT 1", (room_id, device_id))
        if row and str(row["account_type"] or "") == "creator":
            return True
    except Exception:
        pass
    try:
        import sqlite3 as _v405_sqlite3
        from pathlib import Path as _v405_Path
        account_db = _v405_Path(ROOT) / "data" / "account_security_v249382.sqlite3"
        if not account_db.exists():
            return False
        con = _v405_sqlite3.connect(str(account_db), timeout=5)
        try:
            row = con.execute(
                "SELECT professional_enabled FROM accounts_v249382 WHERE room_id=? AND device_id=? LIMIT 1",
                (str(room_id or "ithaki-phone-test")[:120], str(device_id or "")[:180]),
            ).fetchone()
            return bool(row and int(row[0] or 0) == 1)
        finally:
            con.close()
    except Exception:
        return False

_V405_VIDEO_HINT_RE'''
source, count = re.subn(helper_pattern, helper_replacement, source, count=1)
if count != 1:
    raise SystemExit('ERROR: V405 creator helper not patched')
source = source.rstrip() + '\n\n'
for route_file in route_files:
    source += route_file.read_text(encoding='utf-8', errors='strict').strip() + '\n\n'
source += '''# BEGIN V249383_V411_INSTALL
try:
    from v411_live_wall_v249383 import install_v411 as _install_v411_v249383
    _install_v411_v249383(app, ROOT)
except Exception:
    LOG.exception("V249383 V411 live wall reactions failed to install")
# END V249383_V411_INSTALL
'''
exact_checks = {
    version: 1,
    '# BEGIN V249383_PROFESSIONAL_CENTER_ANALYTICS_LIVE_WALL_ROUTES': 1,
    '# BEGIN V249384_PROFESSIONAL_ACTIVATION_BACKUP_FEED_CLEAN_ROUTES': 1,
    '# BEGIN V249385_STABLE_PROFESSIONAL_GLOBAL_FRIEND_GATE_ROUTES': 1,
    '# BEGIN V249386_PRO_CODE_CONFIRMATION_GLOBAL_FRIEND_CONTINUATION_ROUTES': 1,
    '# BEGIN V249387_CREATOR_PUBLIC_LINK_PUBLICATION_WORKSPACE_ROUTES': 1,
    '@app.post("/api/account/v249383/professional/session/validate")': 1,
    '@app.get("/@{creator_slug}", response_class=HTMLResponse)': 1,
    'from v411_live_wall_v249383 import install_v411': 1,
}
for marker, expected in exact_checks.items():
    actual = source.count(marker)
    if actual != expected:
        raise SystemExit(f'ERROR: {marker!r} count={actual}, expected={expected}')
for marker in (
    '/api/creator/views/summary_v249405',
    '/creator-analytics-v249406d',
    '/creator-view-quality-v249407',
    '/creator-message-shares-v249408',
    '/creator-best-time-v249409',
    '/creator-scheduled-posts-v249410',
    '/api/creator/public/v249387/save',
    '/api/creator/public/v249387/analytics',
    'creator_public_v249387',
    'account_security_v249382.sqlite3',
):
    if marker not in source:
        raise SystemExit(f'ERROR: missing {marker!r}')
routes = re.findall(r'@app\.(get|post|put|delete|patch)\(\s*[rfbu]*["\']([^"\']+)["\']', source)
seen = set()
duplicates = []
for route in routes:
    if route in seen:
        duplicates.append(route)
    seen.add(route)
if duplicates:
    raise SystemExit('ERROR duplicate routes ' + repr(duplicates[:20]))
tmp = server.with_suffix(server.suffix + '.v249387.tmp')
with tmp.open('w', encoding='utf-8') as handle:
    handle.write(source.rstrip() + '\n')
tmp.replace(server)
print('VERSION=' + version)
print('FASTAPI_LITERAL_ROUTES=' + str(len(routes)))
print('UNIFIED_PROFESSIONAL_CREATOR_GATE=1')
print('V405_TO_V410_ROUTES=PRESERVED')
print('V411_INSTALL=1')
print('V249386_PRO_CODE_CONFIRMATION_GLOBAL_FRIEND_CONTINUATION=PRESERVED')
print('V249387_CREATOR_PUBLIC_LINK_PUBLICATION_WORKSPACE=1')
