import argparse
import sys
from pathlib import Path


SCRIPT_DIR = Path(__file__).resolve().parent
if str(SCRIPT_DIR) not in sys.path:
    sys.path.insert(0, str(SCRIPT_DIR))

from validate_acore_quest_metadata import (  # noqa: E402
    build_runtime_quest_availability_conditions,
    load_acore_conditions,
)


def build_lua(conditions_by_quest):
    lines = [
        "--! This file is automatically generated. Do not modify.",
        "-- Generated by tools/generate_acore_quest_availability_conditions.py",
        "-- from AzerothCore's final SourceType 19 conditions.",
        "--",
        "-- Conditions in one inner table are ANDed. The inner tables are ORed.",
        "-- Tuple: {conditionType, value1, value2, value3, negativeCondition}",
        "-- Supported types: aura=1, item=2, zone=4, reputation rank=5, quest rewarded=8,",
        "-- quest taken=9, quest none=14, class=15, achievement=17, spawn mask=19,",
        "-- area=23, spell=25, quest complete=28, daily quest done=43, quest state=47.",
        "",
        "if not QuestieCompat.Is335 then return end",
        "",
        "QuestieCompat.AzerothCoreQuestAvailabilityConditions = {",
    ]

    for quest_id in sorted(conditions_by_quest):
        lines.append(f"    [{quest_id}] = {{")
        for group in conditions_by_quest[quest_id]:
            formatted_conditions = ",".join(
                "{" + ",".join(str(value) for value in condition) + "}"
                for condition in group
            )
            lines.append(f"        {{{formatted_conditions}}},")
        lines.append("    },")

    lines.extend(["}", ""])
    return "\n".join(lines)


def main():
    parser = argparse.ArgumentParser(
        description="Generate Questie's AzerothCore quest availability condition table."
    )
    parser.add_argument(
        "--acore-source",
        default=r"P:\AC\source",
        help="Path to the AzerothCore source tree",
    )
    parser.add_argument(
        "--output",
        default="Compat/AzerothCoreQuestAvailabilityConditions.lua",
        help="Generated Lua output path",
    )
    args = parser.parse_args()

    conditions = build_runtime_quest_availability_conditions(
        load_acore_conditions(Path(args.acore_source))
    )
    output_path = Path(args.output)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    output_path.write_text(build_lua(conditions), encoding="utf-8", newline="\n")

    row_count = sum(
        len(group)
        for groups in conditions.values()
        for group in groups
    )
    print(f"Generated {output_path}")
    print(f"Quests: {len(conditions)}")
    print(f"Conditions: {row_count}")


if __name__ == "__main__":
    main()
