#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
报销助手 · 多用户注册表
=======================
每个使用者一个独立工作区（台账/收件箱/打印包互不可见）：
  报销助手/共享/            规则库 + OCR 二进制（全公司共用）
  报销助手/用户/<uid>/      个人工作区（数据/收件箱、报销台账.json、打印包）
  报销助手/                 = 刘新元本人（历史目录，不改动）

`用户/_index.json` 结构：
  {"<uid>": {"name","email","open_id","home","allow":1}}
uid = 邮箱 @ 前部分（liuziyan / zhaoyunhao / liuxinyuan）
"""
import json
import os

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))   # 报销助手/
INDEX = os.path.join(ROOT, '用户', '_index.json')
SHARED = os.path.join(ROOT, '共享')


def load_index():
    if os.path.exists(INDEX):
        try:
            return json.load(open(INDEX, encoding='utf-8'))
        except Exception:
            pass
    return {}


def save_index(d):
    os.makedirs(os.path.dirname(INDEX), exist_ok=True)
    tmp = INDEX + '.tmp'
    json.dump(d, open(tmp, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
    os.replace(tmp, INDEX)


def uid_of(email='', name=''):
    """邮箱 @ 前部分作 uid；无邮箱时用姓名拼音兜底"""
    e = (email or '').strip().lower()
    if '@' in e:
        return e.split('@')[0]
    return (name or '').strip() or 'unknown'


def by_open_id(open_id):
    for uid, u in load_index().items():
        if u.get('open_id') and u['open_id'] == open_id:
            return uid, u
    return None, None


def get(uid):
    """按 uid 或邮箱/姓名取用户（含 home 绝对路径）"""
    idx = load_index()
    uid = (uid or '').strip().lower()
    if uid in idx:
        return dict(idx[uid], uid=uid)
    if '@' in uid:                                    # 传了邮箱
        k = uid.split('@')[0]
        if k in idx:
            return dict(idx[k], uid=k)
    for k, u in idx.items():                          # 传了姓名
        if u.get('name') == uid:
            return dict(u, uid=k)
    return None


def home_for(uid):
    u = get(uid)
    if not u:
        return None
    home = u.get('home') or os.path.join('用户', u['uid'])
    return home if os.path.isabs(home) else os.path.join(ROOT, home)


def is_allowed(uid):
    u = get(uid)
    return bool(u and u.get('allow'))


def ensure_workspace(uid):
    """建好个人工作区目录结构，返回 home 路径"""
    home = home_for(uid)
    if not home:
        raise KeyError('未注册用户：%s' % uid)
    for d in ('数据', os.path.join('数据', '收件箱'), os.path.join('数据', '收件箱', '已处理'),
              os.path.join('数据', '日志'), '工具', '打印包'):
        os.makedirs(os.path.join(home, d), exist_ok=True)
    return home


# ── 首批开放名单（P2 试点：刘新元 + 刘子研 + 赵云浩）──
SEED = {
    'liuxinyuan': {'name': '刘新元', 'email': 'liuxinyuan@biori.com',
                   'open_id': 'ou_901b790c9afdda4a8f14554962b32664', 'home': '.', 'allow': 1},
    'liuziyan':   {'name': '刘子研', 'email': 'liuziyan@biori.com',
                   'open_id': 'ou_2a926216f8c9bc8a4d53e4b3dc0d251c', 'home': '用户/liuziyan', 'allow': 1},
    'zhaoyunhao': {'name': '赵云浩', 'email': 'zhaoyunhao@biori.com',
                   'open_id': 'ou_7fab49a17fecc17934456d76a45d0ca0', 'home': '用户/zhaoyunhao', 'allow': 1},
}


def seed_missing():
    idx = load_index()
    n = 0
    for uid, u in SEED.items():
        if uid not in idx:
            idx[uid] = u
            n += 1
        elif u.get('allow') and not idx[uid].get('allow'):
            idx[uid]['allow'] = 1
            n += 1
    if n:
        save_index(idx)
    for uid in SEED:
        ensure_workspace(uid)
    return n


if __name__ == '__main__':
    n = seed_missing()
    print('✅ 注册表就绪（新增/更新 %d 条）' % n)
    for uid, u in load_index().items():
        mark = '✅ 已开放' if u.get('allow') else '⏸ 未开放'
        print('   %-12s %-6s %-28s %s ｜ %s' % (uid, u.get('name', ''), u.get('email', ''),
                                               mark, home_for(uid)))
