#!/usr/bin/env python3

from __future__ import annotations

import os
from pathlib import Path


ROOT = Path(__file__).resolve().parents[3]
DATA_TE = ROOT / "data" / "te"
TE_GAMES: tuple[str, ...] = ("tr1", "tr2", "tr3")

GAME_LINKS: dict[tuple[str, str], tuple[str, ...]] = {
    ("tr1", "tr1-custom"): (
        "catalog_item_actions.csv",
        "catalog_lara_anims.csv",
        "catalog_lara_states.csv",
        "catalog_music.csv",
        "catalog_objects.csv",
        "catalog_samples.csv",
        "inv_ring.json5",
        "weapons.json5",
    ),
    ("tr2", "tr2-custom"): (
        "catalog_item_actions.csv",
        "catalog_lara_anims.csv",
        "catalog_lara_states.csv",
        "catalog_music.csv",
        "catalog_objects.csv",
        "catalog_samples.csv",
        "inv_ring.json5",
        "weapons.json5",
    ),
    ("tr3", "tr3-custom"): (
        "catalog_item_actions.csv",
        "catalog_lara_anims.csv",
        "catalog_lara_states.csv",
        "catalog_music.csv",
        "catalog_objects.csv",
        "catalog_samples.csv",
        "inv_ring.json5",
        "weapons.json5",
    ),
}

INJECTION_LINKS: dict[tuple[str, str], tuple[str, ...]] = {
    ("tr1", "tr1-custom"): (
        "crystal.bin",
        "font.bin",
        "gun_glow.bin",
        "lara_animations.bin",
        "lara_extra.bin",
        "lara_guns.bin",
        "lara_outfits.bin",
        "misc_sprites.bin",
        "pda_model.bin",
        "photo.bin",
        "pickup_aid.bin",
        "uzi_sfx.bin",
    ),
    ("tr2", "tr2-custom"): (
        "boat_bits.bin",
        "crystal.bin",
        "font.bin",
        "lara_animations.bin",
        "lara_extra.bin",
        "lara_guns.bin",
        "lara_outfits.bin",
        "misc_sprites.bin",
        "pda_model.bin",
        "photo.bin",
        "pickup_aid.bin",
        "secret_models_gm.bin",
        "secret_models_og.bin",
    ),
    ("tr3", "tr3-custom"): (
        "font.bin",
        "globe_model.bin",
        "lara_animations.bin",
        "lara_extra.bin",
        "lara_guns.bin",
        "lara_outfits.bin",
        "misc_sprites.bin",
        "pda_model.bin",
        "pickup_aid.bin",
        "sparks_gfx.bin",
    ),
}


def remove_te_symlinks() -> None:
    # rglob does not descend into a linked directory, so this removes the link
    # and leaves what it points at alone.
    for path in DATA_TE.rglob("*"):
        if path.is_symlink():
            path.unlink()
    # A directory that held only links is empty now, and would block a link
    # to the whole directory in its place.
    for dirpath, _, _ in os.walk(DATA_TE, topdown=False):
        path = Path(dirpath)
        if path != DATA_TE and not any(path.iterdir()):
            path.rmdir()


def create_symlink(path: Path, target: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.symlink_to(target)


def is_skipped(path: Path) -> bool:
    return path.parent.name == "presets"


def mirror_links(source_dir: Path, target_dir: Path) -> None:
    """Links target_dir to source_dir as a whole where nothing under it is
    skipped, and otherwise links each entry, a subdirectory as a whole where
    it can be."""
    if not source_dir.is_dir():
        return
    if not any(
        is_skipped(path) for path in source_dir.rglob("*") if path.is_file()
    ):
        target_rel = source_dir.relative_to(target_dir.parent, walk_up=True)
        create_symlink(target_dir, str(target_rel))
        return
    for source_path in sorted(source_dir.iterdir()):
        target_path = target_dir / source_path.name
        if source_path.is_dir():
            mirror_links(source_path, target_path)
        elif not is_skipped(source_path):
            target_rel = source_path.relative_to(
                target_path.parent, walk_up=True
            )
            create_symlink(target_path, str(target_rel))


def create_cfg_links() -> None:
    source_dir = ROOT / "data" / "trx" / "ship" / "cfg"
    for game in TE_GAMES:
        target_dir = ROOT / "data" / "te" / game / "Engine" / "cfg"
        mirror_links(source_dir, target_dir)


def create_engine_script_links() -> None:
    ship_dir = ROOT / "data" / "trx" / "ship"
    for game in TE_GAMES:
        engine_dir = ROOT / "data" / "te" / game / "Engine"
        mirror_links(ship_dir / "modules", engine_dir / "modules")
        mirror_links(ship_dir / "scripts", engine_dir / "scripts")


def create_game_script_links() -> None:
    games_dir = ROOT / "data" / "trx" / "ship" / "games"
    for game, custom in GAME_LINKS:
        base_dir = ROOT / "data" / "te" / game / "Engine" / "games"
        source_path = games_dir / game / "scripts" / "_game.lua"
        target_path = base_dir / custom / "scripts" / "_game.lua"
        target_rel = source_path.relative_to(target_path.parent, walk_up=True)
        create_symlink(target_path, str(target_rel))
        # The game script names its own game's modules, so those keep the
        # directory the name points at.
        mirror_links(games_dir / game / "modules", base_dir / game / "modules")


def create_game_links() -> None:
    for (game, custom), names in GAME_LINKS.items():
        base_dir = ROOT / "data" / "te" / game / "Engine" / "games" / custom
        target_prefix = Path("../../../../../trx/ship/games") / game
        (base_dir / "injections").mkdir(parents=True, exist_ok=True)
        for name in names:
            create_symlink(base_dir / name, str(target_prefix / name))


def create_injection_links() -> None:
    for (game, custom), names in INJECTION_LINKS.items():
        base_dir = ROOT / "data" / "te" / game / "Engine" / "games" / custom / "injections"
        target_prefix = Path("../../../../../../trx/ship/games") / game / "injections"
        base_dir.mkdir(parents=True, exist_ok=True)
        for name in names:
            create_symlink(base_dir / name, str(target_prefix / name))


def main() -> None:
    remove_te_symlinks()
    create_cfg_links()
    create_engine_script_links()
    create_game_script_links()
    create_game_links()
    create_injection_links()


if __name__ == "__main__":
    main()
