"""
=============================================================================
CMU 11-642 · 第 1 讲共享模块：search_world.py —— 一个"知道真相"的玩具网络 ToyWeb
=============================================================================

【这个模块是干什么的】
    原课的作业在 ClueWeb09（5 千万个英文网页）上做实验；相关性判断由 NIST 的评估员人工标注，
    而且只标注了一小部分文档（池化 pooling，第 4 讲）。我们没有这样的数据，也不想下载几十 GB。
    所以这里用程序"写"出一个小网络：约一万个英文网页，12 个主题 × 3 个子主题（facet），
    每个网页是"按某个子主题写的"——**这件事是已知的**，于是 36 个信息需求的相关性判断是**完整的**。

    它刻意保留了真实网页里让搜索变难的那些现象（讲义 §1、§8 会逐一用到）：
        - Zipf 分布：少数功能词（the、of、and……）占了大部分词次；还有一条很长的"生僻词"尾巴
          （用音节拼出来的假词，代表人名、地名、拼写错误、罕见词），所以词表随文档数不断增长（Heaps 定律）；
        - 同义词 / 词汇不匹配：car / automobile / vehicle、doctor / physician、flu / influenza……
          每篇文档有自己的"用词习惯"，查询写 car 就找不到只写 automobile 的文档；
        - 歧义词：jaguar（猫 / 车）、python（蛇 / 编程语言）、java（编程语言 / 印尼的岛）、
          apple（苹果派 / 苹果公司 / 苹果树）、virus（流感 / 电脑病毒）……
        - 短语：black hole、interest rate、apple pie……（第 1 讲的 #NEAR 算子要用到）；
        - 词形变化：jaguar / jaguars（复数），需要词干处理（stemming）才能匹配；
        - 5 个字段：title、body、url、keywords（作者写的 meta 关键词）、inlink（别人链接到它时用的锚文本），
          和作业用的 ClueWeb09 索引相同；
        - 网站、超链接与锚文本（第 12 讲 PageRank）；
        - 垃圾网页：关键词堆砌 + 互相链接的"链接农场"（它们永远不相关）；
        - 近似重复的镜像网页、"隐私政策 / 联系我们"之类的样板页面、没有标题的网页。

【它和真实网页的区别（务必记住）】
    文本是按概率"拼"出来的词串，没有语法；主题之间的界限比真实世界清楚；每篇文档最多两个子主题。
    所以这里的数字说明的是**机制和趋势**，不是真实系统的量级。讲义会说明哪些结论能推广。

【主要接口 API】
    build_world(n_docs=10000, seed=642)  → World（同一进程里第二次调用直接返回缓存，不重新生成）
    World.docs          文档列表，docs[i].docid == i（内部编号，从 0 开始）
    World.needs         36 个信息需求（Need：qid、facet、short 短查询、long 长查询、narrative 判断标准）
    World.qrels         {qid: {外部编号 ext_id: 相关等级 1 或 2}}（等级 0 的文档不列出）
    World.links         超链接 [(源 docid, 目标 docid, 锚文本), ...]
    World.doc(ext_id)   按外部编号（如 "tw-00042"）找文档
    World.relevant(qid, min_grade=1)  相关文档的外部编号集合
    facet_info(facet)   某个子主题的词表（中文名、词、短语）
    FIELDS              ("title", "body", "url", "keywords", "inlink")

【运行方式】
    python3 search_world.py      # 生成 ToyWeb，打印统计信息和一篇示例文档（约 5 秒）

【可复现】
    每篇文档用自己的随机数生成器 random.Random("toyweb/<种子>/doc/<编号>")：
    字符串种子经过 SHA-512 变成整数，结果不受 PYTHONHASHSEED 影响，Python 3.9 和 3.13 完全相同。
    改动一篇文档的生成方式，不会牵动其他文档。
"""

import bisect
import math
import random
import time


# ---------------------------------------------------------------------------
# 1. 词表 Vocabulary
# ---------------------------------------------------------------------------

# 功能词（function words）：冠词、介词、代词、助动词……按真实英文里的大致频率排序。
# 它们约占真实英文文本词次的 40%~50%，几乎不携带"主题"信息——这正是"停用词"（stopwords）的来源。
FUNCTION_WORDS = [
    "the", "of", "and", "to", "a", "in", "is", "that", "for", "it", "as", "was", "with", "be", "by",
    "on", "not", "he", "i", "this", "are", "or", "his", "from", "at", "which", "but", "have", "an",
    "had", "they", "you", "were", "their", "one", "all", "we", "can", "her", "has", "there", "been",
    "if", "more", "when", "will", "would", "who", "so", "no", "she", "my", "do", "what", "about",
    "out", "up", "them", "some", "could", "into", "than", "then", "its", "only", "other", "new",
    "also", "how", "our", "these", "your", "any", "may", "should", "where", "most", "very", "such",
    "after", "before", "why", "many", "over", "does", "just", "each", "much", "those", "me", "both",
]

# 一般词（general words）：和任何主题都无关的常用实词，按大致频率排序（越靠前越常见）。
# 后面还有一条用音节拼出来的"生僻词尾巴"（_pseudo_word），代表真实文本里大量只出现一两次的词。
GENERAL_WORDS = [
    "time", "people", "year", "way", "day", "make", "good", "first", "like", "get", "use", "see",
    "know", "work", "take", "best", "find", "information", "great", "help", "world", "home", "life",
    "free", "need", "come", "think", "look", "want", "give", "part", "place", "number", "high",
    "well", "page", "right", "small", "large", "next", "old", "big", "long", "little", "own", "same",
    "back", "last", "different", "important", "public", "group", "case", "week", "company", "system",
    "question", "fact", "point", "month", "lot", "study", "book", "job", "word", "business", "issue",
    "side", "kind", "head", "house", "service", "friend", "power", "hour", "line", "end", "member",
    "city", "name", "idea", "body", "result", "change", "morning", "reason", "research", "moment",
    "family", "school", "student", "country", "problem", "hand", "night", "story", "area", "money",
    "learn", "beginner", "tips", "guide", "plan", "results", "reviews", "latest", "protect", "signs",
    "cost", "start", "try", "show", "move", "live", "bring", "happen", "write", "provide", "stand",
    "lose", "pay", "meet", "include", "continue", "set", "lead", "understand", "watch", "follow",
    "stop", "create", "speak", "read", "allow", "add", "spend", "open", "walk", "offer", "remember",
    "love", "consider", "appear", "buy", "wait", "send", "expect", "build", "stay", "fall", "cut",
    "reach", "remain", "suggest", "raise", "pass", "sell", "require", "report", "decide", "black",
    "white", "real", "early", "local", "easy", "hard", "full", "sure", "low", "late", "general",
    "special", "simple", "clear", "recent", "strong", "possible", "whole", "true", "major", "popular",
    "available", "common", "personal", "social", "national", "human", "short", "single", "certain",
    "cheap", "quick", "happy", "nice", "fine", "green", "blue", "yellow", "gold", "dark", "light",
    "today", "always", "never", "often", "really", "still", "already", "almost", "together", "around",
    "people", "office", "door", "party", "teacher", "child", "level", "experience", "detail", "example",
]

# 网站样板页面（"隐私政策""联系我们"）里的词。
BOILERPLATE_WORDS = [
    "home", "contact", "privacy", "policy", "copyright", "rights", "reserved", "terms", "use", "login",
    "site", "website", "email", "news", "blog", "comment", "post", "links", "menu", "search", "subscribe",
    "account", "register", "password", "cookies", "information", "service", "help", "faq", "map",
]
BOILERPLATE_TITLES = ["Privacy Policy", "Contact Us", "About Us", "Terms of Use", "Site Map", "Login",
                      "Copyright Notice", "Help"]
GENERIC_TITLES = ["Home", "Untitled Document", "Welcome", "Index", "Page 2", "News", "Default Page"]

# 导航性的锚文本：真实网页里大量链接的文字是 "home""next""click here"，几乎不描述目标页面。
NAV_ANCHORS = ["home", "next", "previous", "more", "back", "click here", "read more", "main page",
               "contents", "top"]

# 垃圾网页用的"商业词"（关键词堆砌时和热门查询词混在一起）。
SPAM_WORDS = ["cheap", "free", "best", "deal", "discount", "buy", "sale", "offer", "price", "online",
              "top", "bonus", "win", "cash"]

# 同义词组：查询里写的是第一个（"规范形式" canonical），文档可能用组里的任何一个。
# 每篇文档对每个组有自己的偏好（作者的用词习惯），这就产生了"词汇不匹配"（vocabulary mismatch）。
SYNONYMS = {
    "car": (("car", 0.60), ("automobile", 0.25), ("vehicle", 0.15)),
    "doctor": (("doctor", 0.70), ("physician", 0.30)),
    "flu": (("flu", 0.60), ("influenza", 0.40)),
    "laptop": (("laptop", 0.75), ("notebook", 0.25)),
    "soccer": (("soccer", 0.50), ("football", 0.50)),
    "stock": (("stock", 0.60), ("share", 0.30), ("equity", 0.10)),
    "barbecue": (("barbecue", 0.60), ("bbq", 0.40)),
    "cheap": (("cheap", 0.50), ("inexpensive", 0.25), ("affordable", 0.25)),
}

# 主题与子主题。每个子主题有：中文名 zh、词表 words（越靠前越常用；首字母大写的是专有名词，
# 不加复数、在正文里保持大写）、短语 phrases（相邻出现的固定搭配）。
# 每个主题还有自己的主题词 words，被它的三个子主题共用。
# 注意那些故意出现在多个主题里的歧义词：jaguar、python、java、apple、virus、index、court、
# security、battery、tomato、sugar、electric、hybrid、score、season、attack、notebook……
TOPICS = {
    "animals": {
        "zh": "动物",
        "words": ["animal", "wildlife", "species", "habitat", "wild", "nature", "predator", "prey",
                  "zoo", "conservation", "endangered", "forest", "food", "population", "tail"],
        "facets": {
            "big_cats": {"zh": "大型猫科动物",
                         "words": ["jaguar", "leopard", "tiger", "cat", "lion", "cheetah", "hunt", "cub",
                                   "spots", "rainforest", "jungle", "savanna", "stalk", "roar", "Amazon"],
                         "phrases": ["big cat", "jaguar cub", "amazon rainforest"]},
            "snakes": {"zh": "蛇",
                       "words": ["snake", "python", "cobra", "venom", "reptile", "constrictor", "viper",
                                 "rattlesnake", "bite", "scales", "egg", "coil", "serpent", "boa", "antivenom"],
                       "phrases": ["ball python", "king cobra", "venomous snake"]},
            "birds": {"zh": "鸟类",
                      "words": ["bird", "eagle", "nest", "migration", "hawk", "owl", "feather", "wing", "flock",
                                "beak", "parrot", "sparrow", "flight", "songbird", "birdwatching"],
                      "phrases": ["bald eagle", "bird migration"]},
        },
    },
    "cars": {
        "zh": "汽车",
        "words": ["car", "engine", "drive", "driver", "road", "model", "speed", "dealer", "wheel", "tire",
                  "fuel", "mile", "insurance", "highway", "motor"],
        "facets": {
            "luxury": {"zh": "豪华车",
                       "words": ["jaguar", "luxury", "sedan", "leather", "interior", "coupe", "convertible",
                                 "horsepower", "premium", "british", "design", "performance", "v8", "xf", "trim"],
                       "phrases": ["jaguar xf", "sports car", "luxury sedan"]},
            "electric": {"zh": "电动车",
                         "words": ["electric", "battery", "charging", "range", "charger", "ev", "hybrid",
                                   "emissions", "kwh", "plug", "grid", "solar", "tesla", "recharge", "efficiency"],
                         "phrases": ["electric car", "charging station", "battery range"]},
            "repair": {"zh": "汽车维修",
                       "words": ["repair", "brake", "mechanic", "oil", "transmission", "garage", "maintenance",
                                 "warranty", "replace", "filter", "noise", "leak", "inspection", "diagnose", "pad"],
                       "phrases": ["oil change", "brake pads", "check engine"]},
        },
    },
    "programming": {
        "zh": "编程",
        "words": ["code", "software", "program", "programming", "developer", "function", "language",
                  "library", "bug", "compile", "variable", "syntax", "data", "tutorial", "version"],
        "facets": {
            "python": {"zh": "Python 语言",
                       "words": ["python", "script", "pip", "list", "dictionary", "module", "import",
                                 "interpreter", "indentation", "notebook", "django", "numpy", "pandas",
                                 "flask", "pythonic"],
                       "phrases": ["python script", "list comprehension", "virtual environment"]},
            "java": {"zh": "Java 语言",
                     "words": ["java", "class", "object", "jvm", "interface", "inheritance", "thread",
                               "exception", "bytecode", "garbage", "spring", "maven", "jar", "android", "Oracle"],
                     "phrases": ["java virtual machine", "garbage collection", "object oriented"]},
            "databases": {"zh": "数据库",
                          "words": ["database", "sql", "query", "table", "index", "join", "schema",
                                    "transaction", "row", "column", "key", "record", "postgres", "mysql",
                                    "normalization"],
                          "phrases": ["primary key", "sql query", "relational database"]},
        },
    },
    "cooking": {
        "zh": "烹饪",
        "words": ["recipe", "cook", "kitchen", "dish", "taste", "ingredient", "minute", "cup", "salt",
                  "sugar", "butter", "delicious", "meal", "dinner", "flavor"],
        "facets": {
            "baking": {"zh": "烘焙",
                       "words": ["bake", "oven", "pie", "flour", "dough", "cake", "bread", "crust", "apple",
                                 "yeast", "cookie", "cinnamon", "pastry", "dessert", "egg"],
                       "phrases": ["apple pie", "baking soda", "pie crust"]},
            "pasta": {"zh": "意大利面",
                      "words": ["pasta", "sauce", "tomato", "garlic", "spaghetti", "italian", "olive", "noodle",
                                "basil", "cheese", "parmesan", "lasagna", "boil", "pesto", "carbonara"],
                      "phrases": ["olive oil", "tomato sauce", "al dente"]},
            "grilling": {"zh": "烧烤",
                         "words": ["grill", "barbecue", "steak", "ribs", "smoke", "charcoal", "brisket",
                                   "burger", "marinade", "rub", "chicken", "smoker", "sear", "pork", "fire"],
                         "phrases": ["pulled pork", "charcoal grill"]},
        },
    },
    "astronomy": {
        "zh": "天文",
        "words": ["space", "star", "galaxy", "universe", "astronomer", "orbit", "planet", "sky", "sun",
                  "earth", "light", "NASA", "solar", "moon", "astronomy"],
        "facets": {
            "black_holes": {"zh": "黑洞",
                            "words": ["gravity", "mass", "horizon", "singularity", "collapse", "radiation",
                                      "relativity", "Einstein", "Hawking", "quasar", "spacetime", "wormhole",
                                      "accretion", "density", "event"],
                            "phrases": ["black hole", "event horizon", "supermassive black hole"]},
            "mars": {"zh": "火星",
                     "words": ["Mars", "rover", "martian", "crater", "mission", "dust", "atmosphere", "landing",
                               "rocket", "red", "surface", "ice", "colony", "Curiosity", "Perseverance"],
                     "phrases": ["red planet", "mars rover"]},
            "telescopes": {"zh": "望远镜",
                           "words": ["telescope", "lens", "mirror", "observatory", "Hubble", "image", "infrared",
                                     "optics", "aperture", "Webb", "eyepiece", "magnification", "focus",
                                     "mount", "amateur"],
                           "phrases": ["space telescope", "hubble telescope", "james webb"]},
        },
    },
    "finance": {
        "zh": "金融",
        "words": ["money", "invest", "investment", "financial", "bank", "market", "fund", "rate", "income",
                  "tax", "account", "dollar", "risk", "loan", "economy"],
        "facets": {
            "stocks": {"zh": "股票",
                       "words": ["stock", "dividend", "portfolio", "trading", "investor", "broker", "earnings",
                                 "index", "etf", "volatility", "shareholder", "bull", "bear", "valuation",
                                 "NASDAQ"],
                       "phrases": ["stock market", "index fund", "bear market"]},
            "mortgage": {"zh": "房贷",
                         "words": ["mortgage", "interest", "lender", "refinance", "payment", "credit", "house",
                                   "borrower", "closing", "approval", "fixed", "adjustable", "score",
                                   "appraisal", "equity"],
                         "phrases": ["interest rate", "credit score", "down payment"]},
            "retirement": {"zh": "退休储蓄",
                           "words": ["retirement", "savings", "pension", "401k", "ira", "retire", "annuity",
                                     "contribution", "withdrawal", "age", "plan", "security", "benefit",
                                     "nest", "employer"],
                           "phrases": ["social security", "nest egg", "retirement plan"]},
        },
    },
    "health": {
        "zh": "健康",
        "words": ["health", "doctor", "patient", "disease", "symptom", "treatment", "medical", "hospital",
                  "medicine", "care", "drug", "clinic", "condition", "blood", "therapy"],
        "facets": {
            "diabetes": {"zh": "糖尿病",
                         "words": ["diabetes", "insulin", "glucose", "sugar", "diabetic", "diet", "type",
                                   "carbohydrate", "obesity", "pancreas", "a1c", "metformin", "kidney",
                                   "weight", "exercise"],
                         "phrases": ["blood sugar", "type 2 diabetes"]},
            "flu": {"zh": "流感",
                    "words": ["flu", "vaccine", "virus", "fever", "cough", "infection", "season", "shot",
                              "immune", "contagious", "outbreak", "cold", "antiviral", "epidemic", "sneeze"],
                    "phrases": ["flu shot", "immune system", "sore throat"]},
            "heart": {"zh": "心脏病",
                      "words": ["heart", "cholesterol", "artery", "pressure", "cardiac", "stroke", "attack",
                                "chest", "cardiologist", "rhythm", "valve", "beat", "pulse", "statin",
                                "circulation"],
                      "phrases": ["heart attack", "blood pressure", "heart disease"]},
        },
    },
    "travel": {
        "zh": "旅行",
        "words": ["travel", "trip", "hotel", "flight", "tourist", "visit", "vacation", "tour", "destination",
                  "airport", "booking", "culture", "beach", "island", "ticket"],
        "facets": {
            "paris": {"zh": "巴黎",
                      "words": ["Paris", "museum", "France", "french", "Louvre", "Eiffel", "cafe", "Seine",
                                "croissant", "metro", "Montmartre", "boulevard", "wine", "art", "tower"],
                      "phrases": ["eiffel tower", "notre dame"]},
            "japan": {"zh": "日本",
                      "words": ["Japan", "Tokyo", "Kyoto", "japanese", "temple", "sushi", "train", "shrine",
                                "Osaka", "ramen", "cherry", "blossom", "Fuji", "ryokan", "shinkansen"],
                      "phrases": ["cherry blossom", "bullet train", "mount fuji"]},
            "java_island": {"zh": "印尼爪哇岛",
                            "words": ["Java", "Indonesia", "Bali", "volcano", "Jakarta", "temple", "rice",
                                      "Borobudur", "coffee", "tropical", "surf", "terrace", "jungle",
                                      "Yogyakarta", "monsoon"],
                            "phrases": ["java island", "rice terraces", "bali beach"]},
        },
    },
    "music": {
        "zh": "音乐",
        "words": ["music", "song", "band", "album", "musician", "concert", "sound", "listen", "artist",
                  "stage", "melody", "rhythm", "note", "lyrics", "studio"],
        "facets": {
            "guitar": {"zh": "吉他",
                       "words": ["guitar", "chord", "string", "amp", "riff", "electric", "acoustic", "pick",
                                 "strum", "solo", "pedal", "fret", "tuning", "rock", "Fender"],
                       "phrases": ["electric guitar", "acoustic guitar"]},
            "jazz": {"zh": "爵士乐",
                     "words": ["jazz", "saxophone", "trumpet", "improvisation", "swing", "blues", "bebop",
                               "trio", "club", "harmony", "groove", "standard", "Miles", "Davis", "Coltrane"],
                     "phrases": ["miles davis", "jazz club"]},
            "classical": {"zh": "古典音乐",
                          "words": ["classical", "piano", "symphony", "orchestra", "Beethoven", "Mozart",
                                    "concerto", "sonata", "composer", "violin", "opera", "conductor", "score",
                                    "chamber", "keys"],
                          "phrases": ["piano sonata", "string quartet"]},
        },
    },
    "sports": {
        "zh": "体育",
        "words": ["game", "team", "player", "season", "coach", "league", "score", "win", "match", "fans",
                  "championship", "ball", "sport", "final", "stadium"],
        "facets": {
            "soccer": {"zh": "足球",
                       "words": ["soccer", "goal", "striker", "penalty", "midfielder", "goalkeeper", "kick",
                                 "pitch", "club", "cup", "FIFA", "offside", "premier", "Messi", "transfer"],
                       "phrases": ["world cup", "premier league", "penalty kick"]},
            "basketball": {"zh": "篮球",
                           "words": ["basketball", "NBA", "dunk", "court", "rebound", "playoff", "hoop",
                                     "dribble", "assist", "guard", "forward", "center", "Lakers", "Jordan",
                                     "shot"],
                           "phrases": ["slam dunk", "three pointer", "free throw"]},
            "tennis": {"zh": "网球",
                       "words": ["tennis", "racket", "serve", "Wimbledon", "court", "ace", "volley", "set",
                                 "tiebreak", "clay", "baseline", "Federer", "Nadal", "grass", "tournament"],
                       "phrases": ["grand slam", "us open"]},
        },
    },
    "tech": {
        "zh": "科技产品",
        "words": ["technology", "computer", "device", "digital", "internet", "online", "user", "app",
                  "screen", "network", "system", "update", "wireless", "smart", "gadget"],
        "facets": {
            "apple_inc": {"zh": "苹果公司",
                          "words": ["apple", "iphone", "mac", "ipad", "macbook", "ios", "store", "Siri",
                                    "airpods", "watch", "keynote", "icloud", "Cupertino", "Jobs", "ipod"],
                          "phrases": ["apple store", "steve jobs", "app store"]},
            "laptops": {"zh": "笔记本电脑",
                        "words": ["laptop", "processor", "cpu", "ram", "keyboard", "battery", "ssd", "display",
                                  "graphics", "gpu", "gaming", "port", "benchmark", "thin", "weight"],
                        "phrases": ["battery life", "gaming laptop"]},
            "security": {"zh": "网络安全",
                         "words": ["security", "password", "virus", "malware", "hacker", "firewall",
                                   "encryption", "phishing", "antivirus", "breach", "attack", "privacy",
                                   "ransomware", "vulnerability", "patch"],
                         "phrases": ["data breach", "computer virus", "two factor authentication"]},
        },
    },
    "gardening": {
        "zh": "园艺",
        "words": ["garden", "plant", "soil", "grow", "seed", "water", "flower", "leaf", "root", "compost",
                  "yard", "spring", "harvest", "organic", "hole"],
        "facets": {
            "orchards": {"zh": "果园",
                         "words": ["tree", "apple", "orchard", "prune", "fruit", "blossom", "graft", "pear",
                                   "cherry", "pest", "cider", "variety", "rootstock", "ripe", "branch"],
                         "phrases": ["apple tree", "fruit tree", "apple orchard"]},
            "roses": {"zh": "玫瑰",
                      "words": ["rose", "bloom", "petal", "thorn", "fragrance", "rosebush", "aphid", "climbing",
                                "hybrid", "tea", "bouquet", "pink", "perennial", "mulch", "stem"],
                      "phrases": ["rose bush", "climbing rose"]},
            "vegetables": {"zh": "蔬菜种植",
                           "words": ["vegetable", "tomato", "lettuce", "carrot", "pepper", "bean", "cucumber",
                                     "squash", "potato", "onion", "raised", "bed", "zucchini", "sprout",
                                     "irrigation"],
                           "phrases": ["raised bed", "vegetable garden"]},
        },
    },
}

# 36 个信息需求（information needs），每个子主题一个，写法模仿 TREC 的 topic：
#     short：短查询（像用户在搜索框里敲的 2~3 个词，TREC 的 <title>）
#     long ：长查询（一句完整的自然语言问题，TREC 的 <description>）
#     narrative：评估员判断相关性的标准（TREC 的 <narrative>）
# 相关性完全由"文档是不是按这个子主题写的、写了多少"决定（见 _grade），和文档里有没有查询词无关——
# 就像真实的评估员读的是意思，不是关键词。
NEEDS = {
    "animals/big_cats": ("jaguar habitat",
                         "Where do jaguars and other big cats live and how do they hunt in the wild?",
                         "Pages about wild big cats (jaguar, leopard, tiger, lion, cheetah): habitat, hunting, "
                         "behavior, conservation. Pages about Jaguar cars are not relevant."),
    "animals/snakes": ("python snake",
                       "What should I know about pythons, cobras and other snakes, including venom and bites?",
                       "Pages about snakes. Pages about the Python programming language are not relevant."),
    "animals/birds": ("bird migration",
                      "How and why do birds such as eagles and hawks migrate, and where do they nest?",
                      "Pages about wild birds, their migration, nests and behavior."),
    "cars/luxury": ("jaguar car",
                    "Reviews of Jaguar luxury cars and other premium sedans: performance, interior and price.",
                    "Pages about luxury cars. Pages about the jaguar animal are not relevant."),
    "cars/electric": ("electric car battery",
                      "How long does the battery of an electric car last and where can I charge it?",
                      "Pages about electric and hybrid vehicles, batteries, range and charging."),
    "cars/repair": ("brake repair",
                    "How do I fix brakes and other common car repair problems at home?",
                    "Pages about car repair and maintenance."),
    "programming/python": ("python tutorial",
                           "I want to learn the Python programming language: scripts, lists, dictionaries "
                           "and modules.",
                           "Pages about programming in Python. Pages about python snakes are not relevant."),
    "programming/java": ("java garbage collection",
                         "How does garbage collection work in the Java virtual machine?",
                         "Pages about the Java programming language. Pages about the island of Java are "
                         "not relevant."),
    "programming/databases": ("sql index",
                              "How do indexes speed up SQL queries in a relational database?",
                              "Pages about databases and SQL."),
    "cooking/baking": ("apple pie recipe",
                       "Find a recipe for homemade apple pie with a flaky crust.",
                       "Pages about baking: pies, cakes, bread, pastry."),
    "cooking/pasta": ("pasta sauce",
                      "How do I make an Italian tomato sauce for spaghetti with garlic and olive oil?",
                      "Pages about cooking pasta and Italian sauces."),
    "cooking/grilling": ("bbq ribs",
                         "Tips for smoking ribs and brisket on a charcoal grill or barbecue smoker.",
                         "Pages about grilling and barbecue."),
    "astronomy/black_holes": ("black hole",
                              "What happens at the event horizon of a black hole?",
                              "Pages about black holes, gravity and relativity."),
    "astronomy/mars": ("mars rover",
                       "What have the rovers on Mars discovered about the red planet?",
                       "Pages about the planet Mars and missions to it."),
    "astronomy/telescopes": ("space telescope",
                             "How do space telescopes like Hubble and James Webb take images of distant galaxies?",
                             "Pages about telescopes and observatories."),
    "finance/stocks": ("stock market",
                       "How should a beginner invest in the stock market, for example with index funds and "
                       "dividends?",
                       "Pages about stocks, investing and stock markets."),
    "finance/mortgage": ("mortgage rates",
                         "How do interest rates and credit scores affect the cost of a home mortgage?",
                         "Pages about mortgages and home loans."),
    "finance/retirement": ("retirement savings",
                           "How much should I save for retirement in a pension or 401k plan?",
                           "Pages about retirement saving and pensions."),
    "health/diabetes": ("diabetes diet",
                        "What diet helps people with type 2 diabetes control their blood sugar?",
                        "Pages about diabetes, its treatment and diet."),
    "health/flu": ("flu vaccine",
                   "Should I get a flu shot, and how does the influenza vaccine protect against the virus?",
                   "Pages about influenza and flu vaccines. Pages about computer viruses are not relevant."),
    "health/heart": ("heart attack symptoms",
                     "What are the warning signs of a heart attack and how is high blood pressure treated?",
                     "Pages about heart disease, heart attacks and blood pressure."),
    "travel/paris": ("paris museums",
                     "Which museums should a tourist visit in Paris besides the Louvre?",
                     "Pages about visiting Paris."),
    "travel/japan": ("tokyo travel",
                     "Planning a trip to Japan: Tokyo, Kyoto, temples and the bullet train.",
                     "Pages about traveling in Japan."),
    "travel/java_island": ("java island",
                           "What are the best places to visit on the island of Java in Indonesia, such as "
                           "volcanoes and temples?",
                           "Pages about traveling on Java and in Indonesia. Pages about the Java programming "
                           "language are not relevant."),
    "music/guitar": ("guitar chords",
                     "How can a beginner learn chords on an acoustic or electric guitar?",
                     "Pages about playing the guitar."),
    "music/jazz": ("jazz history",
                   "Who were the most influential jazz musicians, such as Miles Davis and John Coltrane?",
                   "Pages about jazz and jazz musicians."),
    "music/classical": ("beethoven symphony",
                        "Information about the symphonies and piano sonatas of Beethoven and Mozart.",
                        "Pages about classical music and composers."),
    "sports/soccer": ("world cup soccer",
                      "Which teams have won the soccer World Cup and who are the best strikers?",
                      "Pages about soccer (association football)."),
    "sports/basketball": ("nba playoffs",
                          "Results and highlights of the NBA basketball playoffs.",
                          "Pages about basketball."),
    "sports/tennis": ("wimbledon tennis",
                      "Who has won the most grand slam titles in tennis, such as Wimbledon?",
                      "Pages about tennis."),
    "tech/apple_inc": ("apple iphone",
                       "Reviews of the latest Apple iPhone and other Apple products.",
                       "Pages about Apple Inc. and its products. Pages about apple fruit are not relevant."),
    "tech/laptops": ("laptop battery life",
                     "Which laptop has the best battery life for students?",
                     "Pages about laptop computers."),
    "tech/security": ("computer virus",
                      "How can I protect my computer from viruses, malware and phishing attacks?",
                      "Pages about computer security. Pages about flu viruses are not relevant."),
    "gardening/orchards": ("apple tree pruning",
                           "When and how should I prune apple trees and other fruit trees in an orchard?",
                           "Pages about fruit trees and orchards."),
    "gardening/roses": ("growing roses",
                        "How do I plant and care for roses so that they bloom?",
                        "Pages about growing roses."),
    "gardening/vegetables": ("vegetable garden",
                             "How do I start a vegetable garden with tomatoes and lettuce in raised beds?",
                             "Pages about growing vegetables."),
}

FIELDS = ("title", "body", "url", "keywords", "inlink")

SITE_SUFFIXES = ["hub", "world", "zone", "central", "daily", "guide", "info", "online", "pro", "lab",
                 "net", "base", "corner", "today", "spot", "planet"]
TLDS = ["com", "com", "com", "org", "net", "info", "edu"]

# 生成参数（改动它们会改变整个 ToyWeb 和讲义里的全部数字）
P_FUNCTION = 0.42        # 每个词是功能词的概率
P_TOPICAL_WORD = 0.70    # 在"主题句"里，一个实词来自主题 / 子主题词表的概率（其余来自一般词）
P_FACET_WORD = 0.62      # 主题词表里，来自子主题专属词（而不是主题共用词）的概率
P_TAIL = 0.35            # 一般实词里，来自生僻词尾巴的概率
TAIL_ALPHA = 1.8         # 生僻词尾巴的幂律指数：P(第 r 个生僻词) ∝ r^(-1.8)（r ≥ TAIL_R0）
TAIL_R0 = 300            # 尾巴从第 300 号生僻词开始（Zipf–Mandelbrot 式的"平头"）：如果从 1 开始，
                         # 第 1 号生僻词一个就占尾巴的 43%，尾巴就不成其为"尾巴"了
P_NUMBER = 0.008         # 一般实词变成数字（年份、数量）的概率
P_PLURAL = 0.18          # 主题词加复数的概率
P_PHRASE = 0.35          # 一个主题句插入一个固定短语的概率


# ---------------------------------------------------------------------------
# 2. 小工具
# ---------------------------------------------------------------------------

_ONSETS = ["b", "br", "d", "dr", "f", "g", "gr", "h", "k", "l", "m", "n", "p", "pr", "r", "s", "st",
           "t", "tr", "v", "z", "sh", "ch", "th"]
_VOWELS = ["a", "e", "i", "o", "u", "ai", "ea", "ou"]
_CODAS = ["", "n", "l", "r", "s", "t", "m", "k", "nd", "st"]
_SYLLABLES = [o + v + c for o in _ONSETS for v in _VOWELS for c in _CODAS]   # 24 × 8 × 10 = 1920 个音节


_M2 = len(_SYLLABLES) ** 2          # 两个音节能拼出的词数：1920² = 3,686,400


def _pseudo_word(r):
    """
    第 r 个"生僻词"：把 r 打乱后写成两个（很少三个）音节，拼成一个读得出来的假词。

    【思路】真实文本里有大量只出现一两次的词（人名、地名、术语、拼写错误）。我们不需要它们有意义，
        只需要它们"很多、各不相同、越往后越罕见"。r 和假词一一对应，所以同一个 r 永远是同一个词。
        为什么要"打乱"：如果直接把 r 写成 1920 进制，r = 1, 2, 3…（最常见的几个生僻词）的第一个音节
        全都相同（"banban""banbar"……），看起来像同一个词的变形。x = (r × 2278193 + 104729) mod 1920²
        是 [0, 1920²) 上的一个一一映射（2278193 和 1920² = 2¹⁴·3²·5² 互质；它约等于 0.618 × 1920²，
        即"黄金分割散列"），相邻的 r 会被打散到完全不同的音节。
    【参数】r：正整数（1, 2, 3, ...）
    【返回】小写字符串，例如 "trounsheak"
    【边界】r ≥ 1920²（概率约 5 × 10⁻⁶）时用三个音节。不同的 r 可能拼出同一个字符串
        （例如 "ba"+"nst" 与 "ban"+"st"）——这种碰撞很少，只是让两个生僻词合并，不影响任何结论。
    【Python 小知识】divmod(a, b) 一次返回 (a // b, a % b)。
    """
    n = len(_SYLLABLES)
    if r < _M2:
        x = (r * 2278193 + 104729) % _M2
        hi, lo = divmod(x, n)
        return _SYLLABLES[hi] + _SYLLABLES[lo]
    x = ((r - _M2) * 2278193 + 104729) % (_M2 * n)
    a, rest = divmod(x, _M2)
    hi, lo = divmod(rest, n)
    return _SYLLABLES[a] + _SYLLABLES[hi] + _SYLLABLES[lo]


def _zipf_cum(n, s=1.0, q=0.0):
    """
    长度为 n 的 Zipf（–Mandelbrot）分布的累积权重 [w1, w1+w2, ...]，w_k = 1 / (k + q)^s。

    【思路】把"越靠前越常见"变成具体的概率：第 k 个词的概率与 1/k^s 成正比（Zipf 分布，讲义 §3）。
        q > 0 让排名最靠前的几个元素不那么突出（Mandelbrot 的修正）。
        累积权重配合 bisect（二分查找）可以在 O(log n) 时间里按这个分布抽样。
    【参数】n：元素个数；s：指数（1.0 是经典的 Zipf）；q：平移量（默认 0）
    【返回】长度为 n 的浮点数列表（单调递增，最后一个是总权重）
    """
    cum, total = [], 0.0
    for k in range(1, n + 1):
        total += 1.0 / (k + q) ** s
        cum.append(total)
    return cum


def _pick(rng, items, cum):
    """
    按累积权重 cum 从 items 里抽一个。

    【思路】在 [0, 总权重) 里均匀撒一个点 u，看它落在哪一段——bisect_right 找到第一个 > u 的位置。
    【边界】rng.random() < 1，所以 u < cum[-1]，下标不会越界；min 只是保险。
    【Python 小知识】bisect.bisect_right(列表, x) 在有序列表里二分查找 x 应该插入的位置（C 实现，很快）。
        random.choices 也能做这件事，但每次调用都要建一个列表，在内层循环里慢一些。
    """
    i = bisect.bisect_right(cum, rng.random() * cum[-1])
    return items[min(i, len(items) - 1)]


def _plural(w):
    """
    英文名词的规则复数：box → boxes，berry → berries，cat → cats。

    【边界】已经以 s 结尾的词（spots、gas）不再变化；不处理不规则复数（mouse → mice）。
        真实英文的词形变化复杂得多，这正是第 8 讲"词干处理"要面对的问题。
    """
    if w.endswith("s"):
        return w
    if w.endswith(("x", "z", "ch", "sh")):
        return w + "es"
    if len(w) > 2 and w.endswith("y") and w[-2] not in "aeiou":
        return w[:-1] + "ies"
    return w + "s"


def _title_case(tokens):
    """把标题里的每个实词首字母大写（the、of 等小词保持小写，第一个词总是大写）。"""
    small = {"the", "of", "and", "a", "an", "for", "in", "on", "to", "with", "at", "by", "or"}
    out = []
    for k, t in enumerate(tokens):
        if k > 0 and t in small:
            out.append(t)
        else:
            out.append(t[:1].upper() + t[1:])
    return " ".join(out)


# ---------------------------------------------------------------------------
# 3. 数据结构
# ---------------------------------------------------------------------------

class Doc:
    """
    一个网页。

    【属性】
        docid    内部编号（0 .. N−1），等于它在 World.docs 里的下标；索引和倒排表都用它
        ext_id   外部编号，如 "tw-00042"（和 ClueWeb09 的 "clueweb09-en0000-00-00000" 作用一样：
                 评测文件 qrels 和结果文件 run 里写的都是外部编号）
        kind     "normal"（普通网页）/ "boilerplate"（样板页）/ "spam"（垃圾网页）/ "duplicate"（镜像）
        site     所在网站的域名，如 "wildcatzone.org"
        facet    主子主题，如 "animals/big_cats"；样板页和垃圾网页为 None
        facet2   第二个子主题（约三成网页有），没有则为 None
        share    {子主题: 这篇文档写这个子主题的"份额"}（0~1），相关性等级由它决定（_grade）
        dup_of   镜像网页抄的是哪篇文档（docid），否则为 None
        fields   {"title": 字符串, "body": 字符串, "url": 字符串, "keywords": 字符串（可能为空）,
                  "inlink": 字符串列表（每个元素是一条指向本页的链接的锚文本）}
    【Python 小知识】__slots__ 告诉 Python 这个类只有这几个属性：每个对象省掉一个字典，一万个对象能省不少内存。
    """
    __slots__ = ("docid", "ext_id", "kind", "site", "facet", "facet2", "share", "dup_of", "fields")

    def __init__(self, docid, kind, site):
        self.docid = docid
        self.ext_id = "tw-%05d" % docid
        self.kind = kind
        self.site = site
        self.facet = None
        self.facet2 = None
        self.share = {}
        self.dup_of = None
        self.fields = {}

    def __repr__(self):
        return "Doc(%s, %s, %s)" % (self.ext_id, self.kind, self.facet)


class Need:
    """
    一个信息需求（information need），相当于 TREC 的一个 topic。

    【属性】qid（1..36）、facet（如 "animals/big_cats"）、topic（如 "animals"）、
        short（短查询）、long（长查询）、narrative（判断标准）
    """
    __slots__ = ("qid", "facet", "topic", "short", "long", "narrative")

    def __init__(self, qid, facet, short, long, narrative):
        self.qid = qid
        self.facet = facet
        self.topic = facet.split("/")[0]
        self.short = short
        self.long = long
        self.narrative = narrative

    def __repr__(self):
        return "Need(%d, %s, %r)" % (self.qid, self.facet, self.short)


class World:
    """build_world 的返回值：文档、信息需求、相关性判断、链接、网站。见模块开头的 API 说明。"""

    def __init__(self, n_docs, seed):
        self.n_docs = n_docs
        self.seed = seed
        self.docs = []
        self.needs = []
        self.qrels = {}
        self.links = []
        self.sites = {}          # 域名 → {"topic": 主题或 None/"spam", "docs": [docid, ...]}
        self.build_seconds = 0.0
        self._by_ext = {}

    def doc(self, ext_id):
        """按外部编号找文档。【边界】编号不存在时抛出 KeyError。"""
        return self._by_ext[ext_id]

    def relevant(self, qid, min_grade=1):
        """查询 qid 的相关文档（等级 ≥ min_grade）的外部编号集合。"""
        return {e for e, g in self.qrels[qid].items() if g >= min_grade}

    def need(self, qid):
        """按 qid 找信息需求。"""
        return self.needs[qid - 1]


def facet_keys():
    """全部 36 个子主题的键，按 TOPICS 里书写的顺序：["animals/big_cats", "animals/snakes", ...]。"""
    return [t + "/" + f for t in TOPICS for f in TOPICS[t]["facets"]]


def facet_info(facet):
    """
    某个子主题的词表。

    【参数】facet：如 "animals/big_cats"
    【返回】字典 {"zh": 中文名, "words": [...], "phrases": [...], "topic": 主题名,
                 "topic_zh": 主题中文名, "topic_words": [...]}
    """
    t, f = facet.split("/")
    info = dict(TOPICS[t]["facets"][f])
    info["topic"] = t
    info["topic_zh"] = TOPICS[t]["zh"]
    info["topic_words"] = TOPICS[t]["words"]
    return info


def _grade(share):
    """
    "写了多少"→ 相关性等级：份额 ≥ 0.40 为 2（高度相关），≥ 0.15 为 1（部分相关），否则 0。

    【检索联系】TREC 的 Web track 也用分级相关（0 不相关 / 1 相关 / 2 高度相关）。
        第 4 讲的 nDCG 会用到等级；P@k、MAP 这类二元指标把 1 和 2 都算"相关"。
    """
    if share >= 0.40:
        return 2
    if share >= 0.15:
        return 1
    return 0


# ---------------------------------------------------------------------------
# 4. 生成文档
# ---------------------------------------------------------------------------

class _Samplers:
    """把词表预先变成"可以快速抽样"的形式（累积权重），整个 ToyWeb 共用一份。"""

    def __init__(self):
        self.func = FUNCTION_WORDS
        self.func_cum = _zipf_cum(len(FUNCTION_WORDS), 0.9)
        self.general = GENERAL_WORDS
        # 一般词用 q = 8 的平移：否则排第一的 "time" 会比 "and" 还常见（真实英文里它排五六十名）
        self.general_cum = _zipf_cum(len(GENERAL_WORDS), 1.0, 8.0)
        self.boiler = BOILERPLATE_WORDS
        self.boiler_cum = _zipf_cum(len(BOILERPLATE_WORDS), 0.8)
        self.facet = {}
        self.topic = {}
        for t in TOPICS:
            self.topic[t] = (TOPICS[t]["words"], _zipf_cum(len(TOPICS[t]["words"]), 1.0))
            for f, info in TOPICS[t]["facets"].items():
                self.facet[t + "/" + f] = (info["words"], _zipf_cum(len(info["words"]), 1.0))
        # 生僻词尾巴：P(r ≥ R) = (R / r0)^(−(α−1))，用逆变换抽样 r = ⌊r0 · u^(−1/(α−1))⌋（u 在 (0, 1] 上均匀）
        self.tail_exp = -1.0 / (TAIL_ALPHA - 1.0)
        self.real_words = set(FUNCTION_WORDS) | set(GENERAL_WORDS) | set(BOILERPLATE_WORDS)
        for t in TOPICS:
            self.real_words.update(w.lower() for w in TOPICS[t]["words"])
            for info in TOPICS[t]["facets"].values():
                self.real_words.update(w.lower() for w in info["words"])
        self._tail_cache = {}

    def tail_word(self, rng):
        """抽一个生僻词。【边界】和真实词表撞车时（极少）在后面加 "x"，保证生僻词不会冒充主题词。"""
        r = int(TAIL_R0 * (1.0 - rng.random()) ** self.tail_exp)
        w = self._tail_cache.get(r)
        if w is None:
            w = _pseudo_word(r)
            if w in self.real_words:
                w += "x"
            self._tail_cache[r] = w
        return w


def _doc_style(rng):
    """这篇文档的"用词习惯"：每个同义词组选一个偏好的说法（按 SYNONYMS 里的权重）。"""
    style = {}
    for canon in sorted(SYNONYMS):
        variants = SYNONYMS[canon]
        u, acc = rng.random(), 0.0
        choice = variants[-1][0]
        for v, p in variants:
            acc += p
            if u < acc:
                choice = v
                break
        style[canon] = choice
    return style


def _surface(rng, w, style, inflect=True):
    """
    把词表里的词变成文档里实际出现的样子：同义词替换 → 复数变化。

    【思路】作者有固定的用词习惯：85% 的时候用自己偏好的说法，15% 的时候随手换一个。
        专有名词（词表里首字母大写）原样保留，不加复数。
    """
    if w[0].isupper():
        return w
    if w in SYNONYMS:
        if rng.random() < 0.85:
            w = style[w]
        else:
            w = rng.choice(SYNONYMS[w])[0]
    if inflect and rng.random() < P_PLURAL:
        w = _plural(w)
    return w


def _general_token(rng, S):
    """一个一般实词：常用词表（Zipf）、生僻词尾巴（幂律）或数字。"""
    u = rng.random()
    if u < P_NUMBER:
        return str(rng.randint(1, 2025))
    if u < P_NUMBER + P_TAIL:
        return S.tail_word(rng)
    return _pick(rng, S.general, S.general_cum)


def _content_token(rng, S, facet, style):
    """主题句里的一个实词：子主题专属词 / 主题共用词 / 一般词。"""
    if rng.random() < P_TOPICAL_WORD:
        if rng.random() < P_FACET_WORD:
            words, cum = S.facet[facet]
        else:
            words, cum = S.topic[facet.split("/")[0]]
        return _surface(rng, _pick(rng, words, cum), style)
    return _general_token(rng, S)


def _sentence(rng, S, facet, style):
    """
    生成一个句子（词的列表）。facet 为 None 时是"一般句"（不谈任何主题）。

    【思路】每个位置先决定是不是功能词（42%），不是的话按句子的主题选实词；
        主题句有 35% 的机会插入一个子主题的固定短语（短语里的词相邻出现，#NEAR 才有东西可找）。
        句首词首字母大写，结尾加句号——让原始文本看起来像文本（分词器会把这些都去掉）。
    """
    n = rng.randint(6, 18)
    toks = []
    for _ in range(n):
        if rng.random() < P_FUNCTION:
            toks.append(_pick(rng, S.func, S.func_cum))
        elif facet is None:
            toks.append(_general_token(rng, S))
        else:
            toks.append(_content_token(rng, S, facet, style))
    if facet is not None and rng.random() < P_PHRASE:
        phrases = TOPICS[facet.split("/")[0]]["facets"][facet.split("/")[1]]["phrases"]
        p = rng.choice(phrases).split()
        k = rng.randint(0, len(toks))
        toks[k:k] = p
    if rng.random() < 0.3 and len(toks) > 4:
        toks[rng.randint(1, len(toks) - 2)] += ","
    toks[0] = toks[0][:1].upper() + toks[0][1:]
    return toks


def _body(rng, S, plan, style, length, lead):
    """
    正文：一句一句生成，直到达到目标长度。

    【参数】plan：[(子主题或 None, 概率), ...]——每一句按这个分布决定谈哪个子主题（或不谈主题）；
        lead：第一句一定谈这个子主题（真实网页的开头通常就点题；否则一篇很短的"蛇"网页
        可能一个和蛇有关的词都没有，却被判为相关）
    【返回】字符串
    """
    keys = [k for k, _ in plan]
    cum, acc = [], 0.0
    for _, p in plan:
        acc += p
        cum.append(acc)
    sents, count = [], 0
    while count < length:
        f = lead if not sents else _pick(rng, keys, cum)
        s = _sentence(rng, S, f, style)
        sents.append(" ".join(s) + ".")
        count += len(s)
    return " ".join(sents)


def _title(rng, S, facet, style, site_label):
    """标题：短语 + 几个主题词，有时带网站名；5% 的网页标题是 "Home""Untitled Document" 之类的废话。"""
    if rng.random() < 0.05:
        return rng.choice(GENERIC_TITLES)
    t, f = facet.split("/")
    info = TOPICS[t]["facets"][f]
    toks = []
    if rng.random() < 0.45:
        toks.extend(rng.choice(info["phrases"]).split())
    for _ in range(rng.randint(1, 4)):
        if rng.random() < 0.7:
            words, cum = S.facet[facet]
        else:
            words, cum = S.topic[t]
        toks.append(_surface(rng, _pick(rng, words, cum), style, inflect=rng.random() < 0.5))
        if rng.random() < 0.2:
            toks.append(rng.choice(["and", "of", "for", "the", "in"]))
    if toks[-1] in ("and", "of", "for", "the", "in"):
        toks.pop()
    title = _title_case(toks)
    if rng.random() < 0.35:
        title += " | " + site_label
    return title


def _keywords(rng, S, facet, style):
    """meta 关键词：35% 的普通网页有，3~7 个主题词，用逗号隔开。"""
    if rng.random() >= 0.35:
        return ""
    t = facet.split("/")[0]
    out = []
    for _ in range(rng.randint(3, 7)):
        words, cum = S.facet[facet] if rng.random() < 0.7 else S.topic[t]
        w = _surface(rng, _pick(rng, words, cum), style, inflect=False).lower()
        if w not in out:
            out.append(w)
    return ", ".join(out)


def _url(rng, site, title_tokens):
    """
    网址：http://www.<网站>/<路径>。路径有时由标题词用 "-" 连接，有时连写成一个词（jaguarspeed），
    有时是 page.php?id=4821 这样的数字——这正是真实 url 字段的样子（第 8 讲讨论怎样切分）。
    """
    u = rng.random()
    words = [w.lower().strip(",|") for w in title_tokens if w.isalpha()][:3]
    if u < 0.2 or not words:
        path = "page.php?id=%d" % rng.randint(100, 99999)
    elif u < 0.3:
        path = "articles/%d" % rng.randint(1, 9999)
    elif u < 0.45:
        path = "".join(words) + ".html"
    else:
        path = "-".join(words) + ".html"
    return "http://www.%s/%s" % (site, path)


def _mutate(rng, S, text, rate):
    """镜像网页：把文本里 rate 比例的词换成一般词，再加一行版权声明。"""
    toks = text.split(" ")
    for k in range(len(toks)):
        if rng.random() < rate:
            toks[k] = _general_token(rng, S)
    return " ".join(toks) + " Copyright mirror site, all rights reserved."


def _make_sites(wr):
    """
    建网站：每个主题 24 个、一般网站 16 个、垃圾网站 6 个。网站名由一个主题词（或生僻词）+ 后缀拼成。

    【返回】(sites, by_topic)：sites = {域名: {"topic": ..., "docs": []}}；
        by_topic = {主题或 None 或 "spam": [域名, ...]}（列表里越靠前的网站越大）
    """
    sites, by_topic = {}, {}
    S = _Samplers()

    def new_site(stem, topic):
        while True:
            name = "%s%s.%s" % (stem, wr.choice(SITE_SUFFIXES), wr.choice(TLDS))
            if name not in sites:
                break
            stem += wr.choice("abcdefghk")
        sites[name] = {"topic": topic, "docs": []}
        by_topic.setdefault(topic, []).append(name)

    for t in TOPICS:
        pool = [w.lower() for w in TOPICS[t]["words"]]
        for info in TOPICS[t]["facets"].values():
            pool += [w.lower() for w in info["words"][:6]]
        for _ in range(24):
            new_site(wr.choice(pool), t)
    for _ in range(16):
        new_site(S.tail_word(wr), None)
    for _ in range(6):
        new_site(wr.choice(SPAM_WORDS) + wr.choice(SPAM_WORDS) + str(wr.randint(1, 99)), "spam")
    return sites, by_topic


def _site_label(site):
    """网站的显示名：域名去掉后缀、首字母大写，例如 "wildcatzone.org" → "Wildcatzone"。"""
    return site.split(".")[0].capitalize()


def _gen_normal(doc, rng, S, facet, facet2):
    """
    生成一篇普通网页。

    【思路】先决定这篇文档"谈主题的程度"t（0.35~0.9：其余句子是闲话），再决定主子主题和
        第二个子主题各占多少（第二个子主题占主题句的 15%~45%）。这些份额就是相关性判断的依据。
    """
    t = rng.uniform(0.35, 0.9)
    plan = [(None, 1.0 - t)]
    if facet2 is None:
        plan.append((facet, t))
        doc.share = {facet: t}
    else:
        w2 = rng.uniform(0.15, 0.45)
        plan += [(facet, t * (1 - w2)), (facet2, t * w2)]
        doc.share = {facet: t * (1 - w2), facet2: t * w2}
    style = _doc_style(rng)
    length = int(min(4000, max(15, rng.lognormvariate(math.log(180), 0.75))))
    title = _title(rng, S, facet, style, _site_label(doc.site))
    doc.fields["title"] = title
    doc.fields["body"] = _body(rng, S, plan, style, length, facet)
    doc.fields["keywords"] = _keywords(rng, S, facet, style)
    doc.fields["url"] = _url(rng, doc.site, title.split(" ") if title not in GENERIC_TITLES else [])


def _gen_boilerplate(doc, rng, S):
    """样板页：标题是 "Privacy Policy" 之类，正文是网站样板词 + 功能词，很短。"""
    title = rng.choice(BOILERPLATE_TITLES)
    toks = []
    for _ in range(rng.randint(15, 80)):
        u = rng.random()
        if u < 0.4:
            toks.append(_pick(rng, S.func, S.func_cum))
        elif u < 0.8:
            toks.append(_pick(rng, S.boiler, S.boiler_cum))
        else:
            toks.append(_general_token(rng, S))
    doc.fields["title"] = title
    doc.fields["body"] = " ".join(toks) + "."
    doc.fields["keywords"] = ""
    doc.fields["url"] = "http://www.%s/%s.html" % (doc.site, "-".join(title.lower().split()))


def _gen_spam(doc, rng, S, facets):
    """
    垃圾网页：关键词堆砌（keyword stuffing）。挑 3 个子主题，把每个子主题最热门的 2 个词
    （例如 flu、vaccine）反复写几十遍，再夹杂一些商业词（cheap、free、deal……）。

    【检索联系】只看词频（tf）打分的模型（Ranked Boolean）会把这种页面排得很高——讲义 §7 的实验，
        也是 1990 年代中期搜索引擎真实遇到的问题；第 2 讲的 BM25 用"词频饱和"抑制它，
        第 12 讲用链接分析识别它。
    """
    targets = rng.sample(facets, 3)
    stuffed = []
    for f in targets:
        stuffed += [w.lower() for w in S.facet[f][0][:2]]
    toks = []
    for _ in range(rng.randint(200, 800)):
        u = rng.random()
        if u < 0.45:
            toks.append(rng.choice(stuffed))
        elif u < 0.55:
            toks.append(rng.choice(SPAM_WORDS))
        elif u < 0.85:
            toks.append(_pick(rng, S.func, S.func_cum))
        else:
            toks.append(_general_token(rng, S))
    words = stuffed + rng.sample(SPAM_WORDS, 4)
    doc.fields["title"] = _title_case(rng.sample(words, 6))
    doc.fields["body"] = " ".join(toks) + "."
    doc.fields["keywords"] = ", ".join(rng.sample(words, 10))
    doc.fields["url"] = "http://www.%s/%s.html" % (doc.site, "-".join(rng.sample(stuffed, 3)))


def _gen_duplicate(doc, rng, S, src):
    """镜像网页：抄另一篇普通网页的标题、正文和关键词，改动 3% 的词，放在另一个网站上。"""
    doc.facet, doc.facet2, doc.share = src.facet, src.facet2, dict(src.share)
    doc.dup_of = src.docid
    doc.fields["title"] = src.fields["title"]
    doc.fields["body"] = _mutate(rng, S, src.fields["body"], 0.03)
    doc.fields["keywords"] = src.fields["keywords"]
    doc.fields["url"] = "http://www.%s/mirror/%s" % (doc.site, src.fields["url"].split("/")[-1])


def _anchor(rng, S, target, docs):
    """
    一条链接的锚文本（anchor text）：大多是目标页面标题里的一两个词——锚文本是"别人怎样描述你"，
    所以它常常比页面自己的文字更像查询（第 8、12 讲）。也有不少是 "click here""home" 这种废话。
    """
    d = docs[target]
    if d.kind == "spam":
        return " ".join(d.fields["title"].lower().split()[:3])
    u = rng.random()
    if u < 0.15:
        return rng.choice(NAV_ANCHORS)
    words = [w.strip(",|").lower() for w in d.fields["title"].split()]
    words = [w for w in words if w.isalpha() and w not in ("the", "of", "and", "for", "in")]
    if u < 0.80 and words:
        k = rng.randint(1, min(3, len(words)))
        start = rng.randint(0, len(words) - k)
        return " ".join(words[start:start + k])
    if d.facet is not None:
        words, cum = S.facet[d.facet]
        return _pick(rng, words, cum).lower()
    return rng.choice(NAV_ANCHORS)


def _make_links(world, wr, S):
    """
    生成超链接和每篇文档的 inlink 字段。

    【思路】每篇文档有一个"人气"（帕累托分布，少数网页极受欢迎）。普通网页的出链：30% 指向同一网站
        （导航链接），45% 指向同主题的网页，25% 指向任意网页，目标按人气抽样；
        垃圾网页互相链接（链接农场 link farm），也有少量普通网页被垃圾评论链到垃圾网页。
    """
    docs = world.docs
    pop = []
    for d in docs:
        if d.kind == "normal":
            pop.append(wr.paretovariate(1.3))
        elif d.kind == "duplicate":
            pop.append(0.3)
        elif d.kind == "boilerplate":
            pop.append(0.2)
        else:
            pop.append(0.05)
    by_topic = {}
    for d in docs:
        if d.kind in ("normal", "duplicate"):
            by_topic.setdefault(d.facet.split("/")[0], []).append(d.docid)
    topic_cum = {}
    for t, ids in by_topic.items():
        acc, cum = 0.0, []
        for i in ids:
            acc += pop[i]
            cum.append(acc)
        topic_cum[t] = (ids, cum)
    all_ids = [d.docid for d in docs if d.kind != "spam"]
    acc, all_cum = 0.0, []
    for i in all_ids:
        acc += pop[i]
        all_cum.append(acc)
    spam_ids = [d.docid for d in docs if d.kind == "spam"]
    seen = set()
    links = []
    for d in docs:
        if d.kind == "spam":
            outs = [wr.choice(spam_ids) for _ in range(wr.randint(15, 40))]
        else:
            k = 0 if d.kind == "boilerplate" and wr.random() < 0.5 else \
                int(min(60, wr.lognormvariate(math.log(4), 0.8)))
            outs = []
            same_site = world.sites[d.site]["docs"]
            topic = d.facet.split("/")[0] if d.facet else None
            for _ in range(k):
                u = wr.random()
                if u < 0.30 and len(same_site) > 1:
                    outs.append(wr.choice(same_site))
                elif u < 0.75 and topic is not None:
                    outs.append(_pick(wr, *topic_cum[topic]))
                elif u < 0.99:
                    outs.append(_pick(wr, all_ids, all_cum))
                elif spam_ids:
                    outs.append(wr.choice(spam_ids))
        for t in outs:
            if t != d.docid and (d.docid, t) not in seen:
                seen.add((d.docid, t))
                links.append((d.docid, t, _anchor(wr, S, t, docs)))
    links.sort()
    world.links = links
    for d in docs:
        d.fields["inlink"] = []
    for s, t, a in links:
        docs[t].fields["inlink"].append(a)


_CACHE = {}


def build_world(n_docs=10000, seed=642):
    """
    生成 ToyWeb。

    【思路】分四步：
        1. 规划（一个"世界级"随机数生成器 wr）：建网站；给每篇文档定种类（普通 87% / 样板 6% /
           垃圾 2% / 镜像 5%）、主子主题（按子主题的流行度抽样）、第二子主题（30%）、所在网站；
        2. 逐篇生成文字（每篇文档自己的随机数生成器）；
        3. 生成超链接和锚文本（inlink 字段）；
        4. 由每篇文档的"份额"算出 36 个信息需求的相关性判断（完整标注，每篇文档都判断）。
    【参数】n_docs：文档数（默认 10000）；seed：种子（默认 642，取自课号）
    【返回】World
    【边界】同一进程里用相同参数再次调用，直接返回第一次的结果（不重新生成）。
        后面的脚本可以放心地多次调用 build_world()。n_docs 太小（< 200）时某些子主题可能没有文档。
    """
    key = (n_docs, seed)
    if key in _CACHE:
        return _CACHE[key]
    t0 = time.perf_counter()
    world = World(n_docs, seed)
    wr = random.Random("toyweb/%d/world" % seed)
    S = _Samplers()
    world.sites, sites_by_topic = _make_sites(wr)
    facets = facet_keys()
    order = facets[:]
    wr.shuffle(order)
    fcum, acc = [], 0.0
    for k in range(len(order)):
        acc += 1.0 / (k + 1) ** 0.7
        fcum.append(acc)
    site_cum = {t: _zipf_cum(len(names), 1.0) for t, names in sites_by_topic.items()}

    # ---- 第 1 步：规划 ----
    plans = []
    for i in range(n_docs):
        u = wr.random()
        if u < 0.02:
            kind = "spam"
        elif u < 0.08:
            kind = "boilerplate"
        elif u < 0.13 and i > 50:
            kind = "duplicate"
        else:
            kind = "normal"
        facet = facet2 = None
        if kind == "normal":
            facet = _pick(wr, order, fcum)
            if wr.random() < 0.30:
                facet2 = _pick(wr, order, fcum)
                if facet2 == facet:
                    facet2 = None
            topic = facet.split("/")[0]
            site = _pick(wr, sites_by_topic[topic], site_cum[topic])
        elif kind == "boilerplate":
            site = wr.choice(sorted(world.sites))
        elif kind == "spam":
            site = wr.choice(sites_by_topic["spam"])
        else:
            site = wr.choice(sites_by_topic[None] + sites_by_topic[wr.choice(list(TOPICS))])
        plans.append((kind, facet, facet2, site))

    # ---- 第 2 步：逐篇生成 ----
    normal_so_far = []
    for i, (kind, facet, facet2, site) in enumerate(plans):
        doc = Doc(i, kind, site)
        rng = random.Random("toyweb/%d/doc/%d" % (seed, i))
        if kind == "duplicate" and not normal_so_far:
            kind = doc.kind = "normal"
            facet = facets[i % len(facets)]
        if kind == "normal":
            doc.facet, doc.facet2 = facet, facet2
            _gen_normal(doc, rng, S, facet, facet2)
            normal_so_far.append(i)
        elif kind == "boilerplate":
            _gen_boilerplate(doc, rng, S)
        elif kind == "spam":
            _gen_spam(doc, rng, S, facets)
        else:
            src = world.docs[rng.choice(normal_so_far)]
            _gen_duplicate(doc, rng, S, src)
        world.docs.append(doc)
        world.sites[site]["docs"].append(i)

    # ---- 第 3 步：链接与锚文本 ----
    _make_links(world, wr, S)

    # ---- 第 4 步：信息需求与完整的相关性判断 ----
    for q, f in enumerate(facets, start=1):
        short, long, narr = NEEDS[f]
        world.needs.append(Need(q, f, short, long, narr))
        judged = {}
        for d in world.docs:
            g = _grade(d.share.get(f, 0.0))
            if g > 0:
                judged[d.ext_id] = g
        world.qrels[q] = judged
    world._by_ext = {d.ext_id: d for d in world.docs}
    world.build_seconds = time.perf_counter() - t0
    _CACHE[key] = world
    return world


# ---------------------------------------------------------------------------
# 5. 自检：直接运行本文件
# ---------------------------------------------------------------------------

def _self_test():
    from console import print_header, print_table, fmt

    w = build_world()
    print_header("ToyWeb：一个知道真相的玩具网络")
    kinds = {}
    for d in w.docs:
        kinds[d.kind] = kinds.get(d.kind, 0) + 1
    print("  文档 %d 篇，网站 %d 个，超链接 %d 条；生成用时 %.1f 秒（计时随机器而变）"
          % (len(w.docs), len(w.sites), len(w.links), w.build_seconds))
    print_table(["种类 kind", "篇数", "比例"],
                [[k, kinds[k], fmt(kinds[k] / len(w.docs))] for k in ("normal", "duplicate", "boilerplate", "spam")])

    print_header("字段的平均长度（按空格切分的词数）")
    rows = []
    for f in FIELDS:
        lens = []
        empty = 0
        for d in w.docs:
            v = d.fields[f]
            n = sum(len(x.split()) for x in v) if isinstance(v, list) else len(v.split())
            lens.append(n)
            empty += n == 0
        rows.append([f, fmt(sum(lens) / len(lens), 1), max(lens), fmt(empty / len(lens))])
    print_table(["字段", "平均词数", "最长", "空字段比例"], rows)

    print_header("相关性判断（完整标注）：每个信息需求有多少篇相关文档")
    rows = []
    for n in w.needs:
        g2 = sum(1 for g in w.qrels[n.qid].values() if g == 2)
        g1 = len(w.qrels[n.qid]) - g2
        rows.append([n.qid, n.facet, n.short, g2, g1])
    print_table(["qid", "子主题", "短查询", "等级 2", "等级 1"], rows)
    sizes = sorted(len(w.qrels[n.qid]) for n in w.needs)
    print("  相关文档数：最少 %d，中位数 %d，最多 %d" % (sizes[0], sizes[len(sizes) // 2], sizes[-1]))

    print_header("一篇示例文档")
    d = w.doc("tw-00042")
    print("  %s  kind=%s  site=%s  facet=%s  facet2=%s" % (d.ext_id, d.kind, d.site, d.facet, d.facet2))
    for f in FIELDS:
        v = d.fields[f]
        s = " ‖ ".join(v) if isinstance(v, list) else v
        print("  [%s] %s" % (f, s[:300] + (" ……" if len(s) > 300 else "")))


if __name__ == "__main__":
    _self_test()
