import sys
import shutil
from pathlib import Path

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8")

PROJECT_ROOT = Path(r"C:\Projects\FreeExile")
WEBAPP_DIR = PROJECT_ROOT / "client" / "webapp"
INDEX_HTML = WEBAPP_DIR / "index.html"
BACKUP_HTML = WEBAPP_DIR / "index.html.bak"

if not BACKUP_HTML.exists():
    shutil.copy2(INDEX_HTML, BACKUP_HTML)
    print(f"Created backup at {BACKUP_HTML}")
else:
    print(f"Using existing source backup at {BACKUP_HTML}")

lines = BACKUP_HTML.read_text(encoding="utf-8").splitlines()

# Dirs
CSS_DIR = WEBAPP_DIR / "css"
JS_DATA_DIR = WEBAPP_DIR / "js" / "data"
JS_ENGINE_DIR = WEBAPP_DIR / "js" / "engine"
JS_UI_DIR = WEBAPP_DIR / "js" / "ui"

for d in [CSS_DIR, JS_DATA_DIR, JS_ENGINE_DIR, JS_UI_DIR]:
    d.mkdir(parents=True, exist_ok=True)

# 1. Extract CSS (lines 22 to 79 -> index 21 to 79)
css_content = "\n".join(lines[21:79]).strip() + "\n"
(CSS_DIR / "main.css").write_text(css_content, encoding="utf-8")
print(f"  OK Generated css/main.css ({len(lines[21:79])} lines)")

# 2. Extract Standard JS Modules
standard_modules = [
    (JS_DATA_DIR / "i18n.js", 2442, 2553, "Internationalization & Master Lexicon"),
    (JS_ENGINE_DIR / "iso_math.js", 2553, 2830, "Isometric Math, Viewport & Camera Shake"),
    (JS_ENGINE_DIR / "joystick.js", 2830, 2945, "Touch Joystick & Pointer Input"),
    (JS_ENGINE_DIR / "audio_haptics.js", 2945, 3007, "AudioContext, Haptics & Sound FX"),
    (JS_ENGINE_DIR / "combat_skills.js", 3007, 3473, "Martial Skills (Fire/Thunder/Frost/Dodge) & Combat VFX"),
    (JS_UI_DIR / "meridian_vault.js", 4601, 4803, "Kỳ Kinh Bát Mạch Matrix, Vault & Guild Stash"),
    (JS_UI_DIR / "shop_megashop.js", 4803, 5159, "The Outcast Bazaar, MegaShop, IAP & Web3 Crypto"),
    (JS_UI_DIR / "seasonal_reset.js", 5159, 5431, "Seasonal League Reset & Remove-Only Stash Tabs"),
    (JS_UI_DIR / "agent_orb.js", 5431, 5803, "AI Agent Delegation & Multi-LLM Thought Stream"),
    (JS_UI_DIR / "worldmap_dungeons.js", 5803, 6274, "World Map, Dungeons & Secret Chambers"),
    (JS_UI_DIR / "hideout_gates.js", 6274, 6480, "Player Hideout, Map Device & Waygates"),
    (JS_UI_DIR / "endgame_atlas.js", 6480, 6945, "Endgame Infinite Atlas & Savage Forge"),
    (JS_UI_DIR / "feedback.js", 6945, 7228, "Settings & Isolated Feedback Telemetry Form"),
    (JS_UI_DIR / "auth.js", 7228, 7620, "Account Auth, Captcha, OTP & OAuth"),
    (JS_UI_DIR / "tooltips.js", 7620, 7688, "Tooltips & Keyboard Shortcuts"),
    (WEBAPP_DIR / "js" / "main.js", 7688, 7789, "Main App Bootstrap & Event Listeners"),
]

for out_path, start_idx, end_idx, desc in standard_modules:
    chunk = "\n".join(lines[start_idx:end_idx]).strip() + "\n"
    out_path.write_text(chunk, encoding="utf-8")
    print(f"  OK Generated {out_path.relative_to(WEBAPP_DIR)} ({end_idx - start_idx} lines) - {desc}")

# 3. Modularize Canvas Engine: Split into world_renderer, vfx_renderer, entity_renderer, canvas_renderer
# 3A. world_renderer.js (lines 3658 to 4053)
world_lines = [
    "// --- WORLD & ENVIRONMENT RENDERER (BIOMES, TILES, TERRAIN, PORTALS, HIDEOUT GATES) ---",
    "function renderWorldEnvironment(ctx, now, dt) {"
]
world_lines.extend(lines[3658:4053])
world_lines.append("}\n")
world_path = JS_ENGINE_DIR / "world_renderer.js"
world_path.write_text("\n".join(world_lines), encoding="utf-8")
print(f"  OK Generated js/engine/world_renderer.js ({len(world_lines)} lines) - World, Terrain, Portals & Waygates")

# 3B. vfx_renderer.js (lines 4082 to 4294, and 4532 to 4596)
vfx_lines = [
    "// --- SAVAGE MARTIAL SKILL VFX & PROJECTILE RENDERER ---",
    "function renderVfxProjectiles(ctx, dt) {"
]
vfx_lines.extend(lines[4082:4294])
vfx_lines.append("}\n")
vfx_lines.append("function renderVfxParticlesAndOverlay(ctx, dt, now) {")
vfx_lines.extend(lines[4532:4596])
vfx_lines.append("}\n")
vfx_path = JS_ENGINE_DIR / "vfx_renderer.js"
vfx_path.write_text("\n".join(vfx_lines), encoding="utf-8")
print(f"  OK Generated js/engine/vfx_renderer.js ({len(vfx_lines)} lines) - Projectiles, Particles & Screen Vignette")

# 3C. entity_renderer.js (lines 4053 to 4082, and 4294 to 4532)
entity_lines = [
    "// --- 2.5D ISOMETRIC ENTITY & CHARACTER SKELETAL RENDERER ---",
    "function renderEntities(ctx, now, dt) {"
]
entity_lines.extend(lines[4053:4082])
entity_lines.extend(lines[4294:4532])
entity_lines.append("}\n")
entity_path = JS_ENGINE_DIR / "entity_renderer.js"
entity_path.write_text("\n".join(entity_lines), encoding="utf-8")
print(f"  OK Generated js/engine/entity_renderer.js ({len(entity_lines)} lines) - Props, Monster, Player & Healthbars")

# 3D. canvas_renderer.js (lines 3473 to 3658 + visual render calls)
canvas_lines = list(lines[3473:3658])
canvas_lines.extend([
    "      // Render Subsystems in Strict Visual Layer Order:",
    "      renderWorldEnvironment(ctx, now, dt);",
    "      renderVfxProjectiles(ctx, dt);",
    "      renderEntities(ctx, now, dt);",
    "      renderVfxParticlesAndOverlay(ctx, dt, now);",
    "",
    "      ctx.restore(); // Restore camera screen shake transformation",
    "",
    "      requestAnimationFrame(renderLoop);",
    "    }",
    "    requestAnimationFrame(renderLoop);\n"
])
canvas_path = JS_ENGINE_DIR / "canvas_renderer.js"
canvas_path.write_text("\n".join(canvas_lines), encoding="utf-8")
print(f"  OK Generated js/engine/canvas_renderer.js ({len(canvas_lines)} lines) - Main 120 FPS Loop & Kinematics")

# 4. Construct Modular index.html
head_part = lines[:20]
head_part.append('  <link rel="stylesheet" href="css/main.css">')

body_part = lines[80:2441]

scripts_part = [
    '  <!-- FreeExile Modularized Engine & UI Scripts (Tam Phân Lập Native ES Architecture) -->',
    '  <script src="js/data/i18n.js"></script>',
    '  <script src="js/engine/iso_math.js"></script>',
    '  <script src="js/engine/joystick.js"></script>',
    '  <script src="js/engine/audio_haptics.js"></script>',
    '  <script src="js/engine/combat_skills.js"></script>',
    '  <script src="js/engine/world_renderer.js"></script>',
    '  <script src="js/engine/vfx_renderer.js"></script>',
    '  <script src="js/engine/entity_renderer.js"></script>',
    '  <script src="js/engine/canvas_renderer.js"></script>',
    '  <script src="js/ui/meridian_vault.js"></script>',
    '  <script src="js/ui/shop_megashop.js"></script>',
    '  <script src="js/ui/seasonal_reset.js"></script>',
    '  <script src="js/ui/agent_orb.js"></script>',
    '  <script src="js/ui/worldmap_dungeons.js"></script>',
    '  <script src="js/ui/hideout_gates.js"></script>',
    '  <script src="js/ui/endgame_atlas.js"></script>',
    '  <script src="js/ui/feedback.js"></script>',
    '  <script src="js/ui/auth.js"></script>',
    '  <script src="js/ui/tooltips.js"></script>',
    '  <script src="js/main.js"></script>',
    '</body>',
    '</html>'
]

new_index_lines = head_part + body_part + scripts_part
new_index_content = "\n".join(new_index_lines) + "\n"
INDEX_HTML.write_text(new_index_content, encoding="utf-8")
print(f"\nSuccessfully refactored index.html:")
print(f"  Before: {len(lines)} lines")
print(f"  After : {len(new_index_lines)} lines (Zero inline CSS, Zero inline JS!)")
