import collections
import datetime
import json
import re
import sys
import urllib.parse
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
OUT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT))

from catalog_prepare import Catalog

WIKI = "https://foreverwiki.org/index.php/"
ZONE_LAYOUT = {
    "Teldrassil": ("Kalimdor", [88, 10, 4.8]),
    "Darkshore": ("Kalimdor", [78, 19, 4.3]),
    "Mount Hyjal": ("Kalimdor", [72, 29, 4.8]),
    "Barrens": ("Kalimdor", [52, 29, 5.0]),
    "Mulgore": ("Kalimdor", [39, 29, 5.0]),
    "Shen'dralas": ("Kalimdor", [32, 20, 4.2]),
    "Orgrimmar": ("Kalimdor", [56, 40, 4.3]),
    "Durotar": ("Kalimdor", [47, 43, 4.3]),
    "Zephras Isle": ("Forever destinations", [48, 13, 6.0]),
    "Tirisfal Glades": ("Eastern Kingdoms", [86, 62, 4.8]),
    "Ruins of Lordaeron": ("Eastern Kingdoms", [87, 74, 3.2]),
    "Silverpine Forest": ("Eastern Kingdoms", [74, 61, 4.1]),
    "Alterac Mountains": ("Eastern Kingdoms", [68, 75, 4.4]),
    "City of Dalaran": ("Eastern Kingdoms", [80, 83, 3.9]),
    "Wetlands": ("Eastern Kingdoms", [56, 72, 4.2]),
    "Dun Morogh": ("Eastern Kingdoms", [46, 79, 4.6]),
    "Hall of Thanes": ("Eastern Kingdoms", [46, 67, 3.1]),
    "Duskwood": ("Eastern Kingdoms", [26, 88, 4.1]),
    "Stormwind City": ("Eastern Kingdoms", [33, 76, 3.8]),
    "Riverglades": ("Forever destinations", [54, 91, 5.1]),
}
ZONE_INFO = {
    "Mount Hyjal": {
        "page": "Mount Hyjal",
        "description": "A new Forever destination, with recovery after Archimonde's defeat and connections to group content.",
        "source": "https://worldofwarcraft.blizzard.com/en-us/news/24315820/world-of-warcraft-forever-now-live",
    },
    "Shen'dralas": {
        "page": "Shen'dralas",
        "description": "A new Forever destination between Mulgore and Desolace.",
        "source": "https://worldofwarcraft.blizzard.com/en-us/news/24315820/world-of-warcraft-forever-now-live",
    },
    "Zephras Isle": {
        "page": "Zephras Isle",
        "description": "The Skyborne starting experience for levels 1–12.",
        "source": "https://worldofwarcraft.blizzard.com/en-us/news/24302071/wow-forever-meet-the-new-skyborne",
    },
    "Riverglades": {
        "page": "Riverglades",
        "description": "A new leveling destination with more than 150 quests across much of the mid-30s to mid-40s experience.",
        "source": "https://worldofwarcraft.blizzard.com/en-us/news/24315820/world-of-warcraft-forever-now-live",
    },
}


def wiki_url(title):
    return WIKI + urllib.parse.quote(title.replace(" ", "_"), safe="():_-'")


def zone_id(name):
    return re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")


def main():
    catalog = Catalog(0)
    verification = json.loads((ROOT / "catalog" / "verification.json").read_text(encoding="utf-8"))
    assert verification["verifiedComplete"] and verification["validNpcTotal"] == 15354
    category_pages = {row["title"] for row in map(json.loads, (ROOT / "catalog" / "verification-categories.jsonl").read_text(encoding="utf-8").splitlines()) if row["status"] == "current"}
    zones = {}
    for name, (group, layout) in ZONE_LAYOUT.items():
        zones[name] = {"id": zone_id(name), "name": name, "group": group, "position": layout[:2], "radius": layout[2], "entries": [], "categories": {}, **ZONE_INFO.get(name, {})}
    for name, description in (("Various", "The source lists various locations; no single point is inferred."), ("Unspecified location", "These matched Forever records have no location field in the current source.")):
        zones[name] = {"id": zone_id(name), "name": name, "group": "Unplaced records", "position": None, "entries": [], "categories": {}, "description": description}
    entries = []
    for entity in catalog.entities.values():
        if entity["kind"] != "npc" or entity["source_status"] != "matched":
            continue
        fields = {field["key"]: field["value"] for field in entity.get("fields", [])}
        raw_location = fields.pop("Location", None)
        location = catalog.location_name(raw_location) if raw_location else None
        matches = re.findall(r"\[\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*\]", raw_location or "")
        assert len(matches) <= 1, entity["key"]
        coordinates = None
        if matches:
            coordinates = [float(matches[0][0]), float(matches[0][1])]
            assert all(0 <= value <= 100 for value in coordinates), entity["key"]
        zone_name = location.split(",")[-1].strip() if location else "Unspecified location"
        assert zone_name in zones, zone_name
        location_category = "Category:WoW Forever NPCs in " + location if location and "Category:WoW Forever NPCs in " + location in category_pages else None
        entry = {
            "id": entity["id"],
            "key": entity["key"],
            "name": entity["display"],
            "title": entity["title"],
            "kind": "mob" if "Category:Forever mobs" in entity.get("source_categories", []) else "npc",
            "zone": zones[zone_name]["id"],
            "zoneName": zone_name,
            "location": location,
            "coordinates": coordinates,
            "fields": fields,
            "wiki": wiki_url(entity["title"]),
            "wowhead": entity["url"],
            "warcraft": entity["source_url"],
            "lastmod": entity.get("lastmod"),
            "locationCategory": wiki_url(location_category) if location_category else None,
        }
        entries.append(entry)
        zone = zones[zone_name]
        zone["entries"].append(entry)
        if location_category:
            key = location or "Unspecified location"
            if key not in zone["categories"]:
                zone["categories"][key] = {"name": location, "url": entry["locationCategory"], "count": 0}
            zone["categories"][key]["count"] += 1
    assert len(entries) == 128
    assert sum(entry["location"] is not None for entry in entries) == 116
    assert sum(entry["coordinates"] is not None for entry in entries) == 80
    zone_list = []
    for zone in zones.values():
        zone["entries"].sort(key=lambda row: (row["name"], row["id"]))
        zone["locatedCount"] = sum(entry["location"] is not None for entry in zone["entries"])
        zone["coordinateCount"] = sum(entry["coordinates"] is not None for entry in zone["entries"])
        zone["mobCount"] = sum(entry["kind"] == "mob" for entry in zone["entries"])
        zone["categories"] = sorted(zone["categories"].values(), key=lambda row: row["name"])
        if "page" in zone:
            zone["wiki"] = wiki_url(zone["page"])
        zone_list.append(zone)
    zone_list.sort(key=lambda row: (row["group"], row["name"]))
    assert len({zone["id"] for zone in zone_list}) == len(zone_list)
    data = {
        "schema": 1,
        "title": "The Forever Atlas",
        "generatedAt": datetime.datetime.now(datetime.timezone.utc).isoformat(),
        "catalogVerifiedAt": verification["checkedAt"],
        "leafletVersion": "1.9.4",
        "stats": {
            "catalogNpcs": verification["validNpcTotal"],
            "matchedNpcs": len(entries),
            "withLocation": sum(entry["location"] is not None for entry in entries),
            "withCoordinates": sum(entry["coordinates"] is not None for entry in entries),
            "coordinateZones": sum(zone["coordinateCount"] > 0 for zone in zone_list),
            "worldZones": len(ZONE_LAYOUT),
            "listedZoneGroups": len(zone_list),
            "withoutLocation": sum(entry["location"] is None for entry in entries),
        },
        "scope": {
            "geometry": "The world index is an original schematic cartogram, not literal geography or Blizzard map artwork. Zone positions are editorial layout only.",
            "coordinates": "Zone views plot exact x/y coordinates extracted from matched Forever-specific Warcraft Wiki records. No coordinates are inferred for missing values.",
            "sources": "Wowhead's dedicated Forever index supplies entity identity. Matched Warcraft Wiki Forever sources supply structured fields under CC BY-SA 4.0. Other-version statistics are not imported.",
            "placeholderWarning": "The full NPC catalog contains 15354 in-scope records, but only 128 have matched Forever-specific supplemental sources. This atlas plots sourced locations only; it is not a complete in-game mob census.",
        },
        "zones": zone_list,
        "npcs": sorted(entries, key=lambda row: (row["zone"], row["name"], row["id"])),
        "links": {
            "wiki": WIKI + "World_of_Warcraft:_Forever",
            "guide": WIKI + "Forever_Atlas",
            "copyrights": WIKI + "Foreverpedia:Copyrights",
            "wowhead": "https://www.wowhead.com/forever/",
            "warcraft": "https://warcraft.wiki.gg/wiki/World_of_Warcraft:_Forever",
            "leaflet": "https://leafletjs.com/",
            "leafletLicense": "vendor/LICENSE.leaflet.txt",
            "codeLicense": "LICENSE.txt",
            "dataLicense": "https://creativecommons.org/licenses/by-sa/4.0/",
        },
    }
    serialized = json.dumps(data, ensure_ascii=False, indent=2) + "\n"
    (OUT / "atlas-data.json").write_text(serialized, encoding="utf-8")
    (OUT / "atlas-data.js").write_text("window.FOREVER_ATLAS = " + serialized, encoding="utf-8")
    report = {
        "generatedAt": data["generatedAt"],
        "stats": data["stats"],
        "zones": [{"name": zone["name"], "located": zone["locatedCount"], "coordinates": zone["coordinateCount"], "listed": len(zone["entries"])} for zone in zone_list],
        "coordinateChecksPassed": True,
        "unsupportedLocationsInvented": 0,
    }
    (OUT / "build-report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps(report["stats"], ensure_ascii=False))


if __name__ == "__main__":
    main()
