#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""验证：访问次数挪到 crawler 列表 + 选中即搜加到 crawler + 预取不计入。"""
import json
import re
import sqlite3
import urllib.request

BASE = "http://127.0.0.1:8000"


def fetch(path, hdrs=None):
    r = urllib.request.urlopen(urllib.request.Request(BASE + path, headers=hdrs or {}), timeout=30)
    return r.read().decode("utf-8", "ignore"), r.getcode()


print("=== ① /crawler/ 页面 ===")
h, code = fetch("/crawler/")
print("  HTTP:", code, " 大小:", len(h))
print("  含选中即搜脚本(selbar)    :", "selbar" in h)
print("  含 encodeURIComponent     :", "encodeURIComponent" in h)
print("  选中脚本跳 originals 搜索 :", "/originals/?q='+encodeURIComponent" in h)
m = re.search(r"window\.__BOOT__ = (\{.*?\});</script>", h, re.S)
if m:
    boot = json.loads(m.group(1))
    items = boot.get("items") or []
    withv = [it for it in items if "v" in it]
    print("  首屏 items 数             :", len(items))
    print("  其中带 v(访问次数)字段的  :", len(withv))
    print("  样例 v 值                 :", [it.get("v") for it in items[:6]])
else:
    print("  ⚠️ 未找到 __BOOT__（可能被登录拦住）")
    print("  页面开头:", h[:200].replace("\n", " "))

print("\n=== ② /originals/ 已去掉访问次数 ===")
h2, _ = fetch("/originals/?q=3392417")
print("  含 class=vc（访问次数）   :", "vc title=" in h2 or "正文被打开的次数" in h2)

print("\n=== ③ 预取 vs 真实打开（直接查 project_visits）===")
db = sqlite3.connect("/root/session.db")
db.execute("PRAGMA busy_timeout=15000")
# 取一个 crawler 记录 id
gov = sqlite3.connect("/root/search.db")
gov.execute("PRAGMA busy_timeout=15000")
rid = gov.execute("SELECT id FROM gov_raw WHERE title IS NOT NULL ORDER BY id DESC LIMIT 1").fetchone()[0]
gov.close()
before = db.execute("SELECT COUNT(*) FROM project_visits WHERE project_type='crawler' AND project_id=?",
                    (str(rid),)).fetchone()[0]
print("  记录 id=%s 当前访问次数 = %d" % (rid, before))

# 模拟预取（不带 view）→ 不应增加


def hit(qs):
    try:
        r = urllib.request.urlopen(BASE + "/api/item?db=crawler&id=%s%s" % (rid, qs), timeout=30)
        d = json.loads(r.read().decode("utf-8", "ignore"))
        return d.get("ok")
    except Exception as e:
        return "ERR:%s" % str(e)[:40]


print("  预取调用(无 view) ok=", hit(""))
after_pre = db.execute("SELECT COUNT(*) FROM project_visits WHERE project_type='crawler' AND project_id=?",
                       (str(rid),)).fetchone()[0]
print("    → 访问次数 = %d  （应保持不变）" % after_pre)

print("  真实打开(view=1) ok=", hit("&view=1"))
after_view = db.execute("SELECT COUNT(*) FROM project_visits WHERE project_type='crawler' AND project_id=?",
                        (str(rid),)).fetchone()[0]
print("    → 访问次数 = %d  （应 +1）" % after_view)
db.close()
print()
print("结论: 预取 %s / 真实打开 %s" % (
    "✅未计数" if after_pre == before else "❌计数了",
    "✅+1" if after_view == after_pre + 1 else "❌未+1"))
