#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""多源订阅聚合生成器

策略：以指定源（base_source）的完整配置为基底，保留它的 proxy-groups / rules / dns，
只做这几件事：
  1. 去掉「跑配置」用的运行字段（mixed-port / external-controller / external-ui 等）
  2. 本地节点插到 proxies 段最前面
  3. 给本地节点单独建一个组（local_group），并放到「默认代理」首位
  4. 其他源的节点追加到 proxies 末尾，并挂进 attach_group
  5. 统一缩进为顶格

如果基底没有 proxy-groups（例如 3x-ui 的订阅），退化为「单个 PROXY 组」结构。
"""
import json, os, sys, re, urllib.request

BASE = "/opt/sub"
CONF = f"{BASE}/sources.json"
OUT  = f"{BASE}/sub.yaml"
LOG  = f"{BASE}/last_result.json"

# 纯订阅不需要的运行字段
RUNTIME_KEYS = {
    "port", "socks-port", "mixed-port", "redir-port", "tproxy-port",
    "allow-lan", "bind-address", "mode", "log-level", "ipv6",
    "external-controller", "external-ui", "external-ui-url", "secret",
    "unified-delay", "tcp-concurrent", "keep-alive-interval", "find-process-mode",
    "profile", "ntp", "interface-name", "routing-mark",
    "geodata-mode", "geox-url", "global-client-fingerprint",
    "authentication", "skip-auth-prefixes", "lan-allowed-ips", "lan-disallowed-ips",
}


def fetch(url, timeout=15):
    req = urllib.request.Request(url, headers={
        "User-Agent": "clash-verge/2.0.0",
        "Accept": "*/*",
    })
    return urllib.request.urlopen(req, timeout=timeout).read().decode("utf-8", "replace")


def dedent(blk):
    ind = [len(x) - len(x.lstrip()) for x in blk if x.strip()]
    m = min(ind) if ind else 0
    return [x[m:] if len(x) >= m else x for x in blk]


def parse_nodes(text):
    lines = text.split("\n")
    start = None
    for i, l in enumerate(lines):
        if re.match(r'^proxies\s*:', l):
            start = i + 1
            break
    if start is None:
        return []
    end = len(lines)
    for i in range(start, len(lines)):
        if re.match(r'^[a-z][a-z0-9_-]*\s*:', lines[i]):
            end = i
            break
    nodes, cur = [], []
    for l in lines[start:end]:
        if re.match(r'^\s*-\s+name\s*:', l):
            if cur: nodes.append(cur)
            cur = [l]
        elif cur:
            cur.append(l)
    if cur: nodes.append(cur)
    return [dedent(b) for b in nodes]


def node_name(blk):
    for l in blk:
        m = re.match(r'^\s*-\s+name\s*:\s*(.+?)\s*$', l)
        if m:
            return m.group(1).strip().strip('"').strip("'")
    return ""


def local_node_yaml(n):
    out = [f"- name: {n['name']}"]
    order = ["type","server","port","password","uuid","network","tls","sni","servername",
             "skip-cert-verify","client-fingerprint","udp","flow","up","down"]
    for k in order:
        if k in n and n[k] is not None:
            v = n[k]
            if isinstance(v, bool):
                out.append(f"  {k}: {'true' if v else 'false'}")
            elif isinstance(v, (int, float)):
                out.append(f"  {k}: {v}")
            else:
                sv = str(v)
                out.append(f'  {k}: "{sv}"' if (" " in sv or sv == "") else f"  {k}: {sv}")
    if n.get("alpn"):
        out.append("  alpn:")
        for a in n["alpn"]:
            out.append(f"    - {a}")
    if n.get("obfs"):
        out.append(f"  obfs: {n['obfs']}")
        if n.get("obfs-password"):
            out.append(f"  obfs-password: {n['obfs-password']}")
    known = set(order) | {"alpn","obfs","obfs-password","name","enable","note"}
    for k, v in n.items():
        if k in known: continue
        out.append(f"  {k}: {v}")
    return out


def normalize_proxies(lines):
    s = e = None
    for i, l in enumerate(lines):
        if re.match(r'^proxies\s*:', l):
            s = i + 1
        elif s is not None and re.match(r'^[a-z][a-z0-9_-]*\s*:', l):
            e = i
            break
    if s is None:
        return lines
    if e is None:
        e = len(lines)
    blk = lines[s:e]
    ind = [len(x) - len(x.lstrip()) for x in blk if x.strip()]
    m = min(ind) if ind else 0
    if m == 0:
        return lines
    nb = [x[m:] if len(x) >= m else x for x in blk]
    return lines[:s] + nb + lines[e:]


def strip_runtime(lines):
    out, skipping = [], False
    for l in lines:
        m = re.match(r'^([a-z][a-z0-9_-]*)\s*:', l)
        if m:
            skipping = m.group(1) in RUNTIME_KEYS
        if not skipping:
            out.append(l)
    return out


def top_marks(lines):
    idx = [i for i, l in enumerate(lines) if re.match(r'^[a-z][a-z0-9_-]*\s*:', l)]
    return idx + [len(lines)]


def section_range(lines, key):
    marks = top_marks(lines)
    for j in range(len(marks) - 1):
        if re.match(r'^' + key + r'\s*:', lines[marks[j]]):
            return marks[j], marks[j + 1]
    return None, None


def build(base_text, extra_blocks, extra_names, local_blocks, local_names, opts):
    group = opts.get("attach_group", "手动选择")
    local_group = opts.get("local_group", "自建")
    lines = base_text.split("\n")
    lines = normalize_proxies(lines)

    if opts.get("strip_runtime_keys", True):
        lines = strip_runtime(lines)

    has_groups = any(re.match(r'^proxy-groups\s*:', l) for l in lines)

    # ---- proxies 段：本地节点插最前，其他源追加末尾 ----
    s, e = section_range(lines, "proxies")
    if s is None:
        lines = ["proxies:"] + lines
        s, e = 0, 1
    front, back = [], []
    for b in local_blocks:     # 本地节点在最前
        front.extend(b)
    for b in extra_blocks:
        back.extend(b)
    lines = lines[:s + 1] + front + lines[s + 1:e] + back + lines[e:]

    if not has_groups:
        names = [node_name(b) for b in local_blocks + extra_blocks]
        body = ["proxy-groups:", f"- name: PROXY", "  type: select", "  proxies:"]
        body += [f"  - {n}" for n in names if n]
        body += ["  - DIRECT", "rules:", "- MATCH,PROXY"]
        return "\n".join(lines + body)

    # ---- 在 proxy-groups 段开头插入「自建」组（select + 内部自动子组）----
    if local_names:
        gs, ge = section_range(lines, "proxy-groups")
        if gs is not None:
            blk = [
                f"  - name: {local_group}",
                "    type: select",
                "    proxies:",
            ] + [f"      - {n}" for n in local_names] + [
                f"      - {local_group}-自动",
            ] + [
                f"  - name: {local_group}-自动",
                "    type: url-test",
                "    url: http://www.gstatic.com/generate_204",
                "    interval: 300",
                "    tolerance: 50",
                "    lazy: false",
                "    proxies:",
            ] + [f"      - {n}" for n in local_names]
            lines = lines[:gs + 1] + blk + lines[gs + 1:]

    # ---- 「默认代理」首位加自建组 ----
    if local_names:
        gs, ge = section_range(lines, "proxy-groups")
        blk = lines[gs:ge]
        for i, l in enumerate(blk):
            if re.match(r'^\s*-?\s*name\s*:\s*默认代理\s*$', l):
                for k in range(i, len(blk)):
                    if re.match(r'^\s*proxies\s*:', blk[k]):
                        blk = blk[:k + 1] + [f"      - {local_group}"] + blk[k + 1:]
                        break
                break
        lines = lines[:gs] + blk + lines[ge:]

    # ---- 其他源节点挂进 attach_group ----
    if extra_names:
        gs, ge = section_range(lines, "proxy-groups")
        blk = lines[gs:ge]
        tgt = None
        for i, l in enumerate(blk):
            if re.match(r'^\s*-?\s*name\s*:\s*' + re.escape(group) + r'\s*$', l):
                tgt = i
                break
        if tgt is None:
            for i, l in enumerate(blk):
                if re.match(r'^\s*-?\s*name\s*:', l):
                    tgt = i
                    break
        if tgt is not None:
            plist, indent = None, "      "
            for i in range(tgt, len(blk)):
                if re.match(r'^\s*proxies\s*:', blk[i]):
                    plist = i
                    for k in range(i + 1, len(blk)):
                        m = re.match(r'^(\s*)-\s+', blk[k])
                        if m:
                            indent = m.group(1)
                            break
                    break
                if i > tgt and re.match(r'^\s*-\s*type\s*:', blk[i]):
                    break
            if plist is not None:
                end = plist + 1
                while end < len(blk):
                    l = blk[end]
                    if not l.strip():
                        end += 1
                    elif re.match(r'^\s*-\s+', l) and not re.match(r'^\s*-\s*(type|name)\s*:', l):
                        end += 1
                    else:
                        break
                add = [f"{indent}- {n}" for n in extra_names]
                blk = blk[:end] + add + blk[end:]
        lines = lines[:gs] + blk + lines[ge:]

    return "\n".join(lines)


def main():
    try:
        cfg = json.load(open(CONF, encoding="utf-8"))
    except Exception as e:
        print("读取配置失败:", e); return 1

    opts = cfg.get("options", {})
    base_source = opts.get("base_source")
    exclude_kw = opts.get("exclude_keywords", []) or []
    add_scv = opts.get("add_skip_cert_verify", True)

    report = {"sources": [], "local": 0, "total": 0, "errors": []}
    base_text = None
    extra_blocks, extra_names = [], []
    local_blocks, local_names = [], []

    for s in cfg.get("sources", []):
        if not s.get("enable", True):
            continue
        try:
            raw = fetch(s["url"])
            nodes = parse_nodes(raw)
            if not nodes:
                report["sources"].append({"name": s["name"], "nodes": 0, "ok": False,
                                          "error": "解析出 0 个节点"})
                report["errors"].append(f"{s['name']}: 0 nodes")
                continue

            kept = []
            for b in nodes:
                nm = node_name(b)
                if any(kw and kw in nm for kw in exclude_kw):
                    continue
                if add_scv:
                    txt = "\n".join(b)
                    if re.search(r'^\s*tls\s*:\s*true', txt, re.M) and "skip-cert-verify" not in txt:
                        nb = []
                        for l in b:
                            nb.append(l)
                            if re.match(r'^\s*tls\s*:\s*true\s*$', l):
                                nb.append("  skip-cert-verify: true")
                        b = nb
                kept.append(b)

            stype = s.get("type", "public")       # public=三方机场, private=自有
            is_base = (s["name"] == base_source) if base_source else (base_text is None)
            if is_base and base_text is None:
                base_text = raw
                report["sources"].append({"name": s["name"], "nodes": len(kept), "ok": True,
                                          "role": "base", "type": stype})
            elif stype == "private":
                # 私有源：节点当作本地节点，排最前，进「自建」组
                local_blocks.extend(kept)
                local_names.extend([node_name(b) for b in kept])
                report["sources"].append({"name": s["name"], "nodes": len(kept), "ok": True, "type": "private"})
            else:
                extra_blocks.extend(kept)
                extra_names.extend([node_name(b) for b in kept])
                report["sources"].append({"name": s["name"], "nodes": len(kept), "ok": True, "type": "public"})
        except Exception as e:
            report["sources"].append({"name": s["name"], "nodes": 0, "ok": False, "error": str(e)[:120]})
            report["errors"].append(f"{s['name']}: {e}")

    for n in cfg.get("local_nodes", []):
        if not n.get("enable", True):
            continue
        b = local_node_yaml(n)
        local_blocks.append(b)
        local_names.append(n["name"])
        report["local"] += 1

    if base_text is None:
        if not local_blocks and not extra_blocks:
            print("没有任何可用节点"); return 1
        base_text = "proxies:\n"

    out = build(base_text, extra_blocks, extra_names, local_blocks, local_names, opts)

    tmp = OUT + ".tmp"
    open(tmp, "w", encoding="utf-8").write(out)
    os.replace(tmp, OUT)

    total = sum(x["nodes"] for x in report["sources"] if x["ok"]) + report["local"]
    report["total"] = total
    import datetime
    report["generated_at"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    json.dump(report, open(LOG, "w"), ensure_ascii=False, indent=1)
    print(f"ok: {total} nodes -> {OUT}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
