"""Restore the full team guide from its retained Markdown, with current method directory."""
from pathlib import Path
from html import escape as esc
from lxml import html,etree
import re,subprocess,json
ROOT=Path(__file__).resolve().parents[2]
SOURCE='work/2026-05-25-team-ai-native-collaboration-guide/TEAM_AI_NATIVE_COLLABORATION_GUIDE.md'
BASE='https://zhctpmt.yyangpt.cn/'
from urllib.parse import urlsplit,unquote,quote

def render_manual():
 text=(ROOT/SOURCE).read_text()
 sections={}
 for m in re.finditer(r'^## (\d+)\. ([^\n]+)\n(.*?)(?=^## |\Z)',text,re.M|re.S):sections[int(m[1])]=(m[2],m[3])
 groups=[('onboarding','新人上手与任务提问',[2]),('files','产品、项目与目录怎么分',[3,4,5,7]),('wedrive','微盘原件、在线表与资料检索',[6]),('delivery-workflow','从提出任务到交付的完整流程',[8,9]),('resources','知识库、项目库与工具总导航',[11]),('methods','需求、战略与产品方法工具箱',[12,13]),('core-skills','高频方法、触发方式与实例',[14]),('skill-usage','方法安装、调用方式与五模块',[16,17]),('templates','可直接复制的完整任务模板',[18]),('team-rules','协作规则与禁止事项',[19,20])]
 blocks=[];audit={'source':SOURCE,'recovered_sections':[],'links':[],'local_only':[],'missing':[]}
 for id,title,nums in groups:
  content='\n\n'.join('### '+sections[n][0]+'\n\n'+sections[n][1] for n in nums)
  # Correct an old broad branch sentence without losing the guidance for business repos.
  content=content.replace('修改前必须读项目规则、建任务分支或独立 worktree','修改前先读目标项目规则；业务仓库按其分支规则执行，控制项目按当前 master 同步规则执行')
  raw=subprocess.check_output(['pandoc','--from=gfm','--to=html5'],input=content,text=True)
  frag=html.fragment_fromstring(raw,create_parent='div')
  for a in frag.xpath('.//a[@href]'):
   href=a.get('href');parsed=urlsplit(href)
   if parsed.scheme and parsed.scheme not in ['http','https']:a.drop_tag();continue
   if href.startswith('#'):continue
   if not parsed.scheme:
    target=((ROOT/SOURCE).parent/unquote(parsed.path)).resolve()
    try:relative=target.relative_to(ROOT).as_posix()
    except ValueError:a.drop_tag();continue
    if not target.exists():audit['missing'].append(relative);a.tag='span';a.attrib.pop('href',None);a.set('title','旧入口待修复：'+relative);continue
    safe=target.suffix in ['.md','.html'] and not re.search(r'local-paths|acceptance-results|runbook|deployment-records|local-config|work_aliyun_ops_agent|work_laidisen',relative)
    if safe:
     a.set('href',BASE+quote(relative,safe='/')+('#'+parsed.fragment if parsed.fragment else ''));a.set('data-team-guide-link','true');a.set('target','_blank');a.set('rel','noopener');audit['links'].append(a.get('href'))
    else:a.tag='span';a.attrib.pop('href',None);a.set('title','在团队授权工作区打开：'+relative);audit['local_only'].append(relative)
  for tag in frag.xpath('.//script|.//iframe|.//form'):tag.drop_tree()
  for table in frag.xpath('.//table'):
   parent=table.getparent();i=parent.index(table);parent.remove(table);wrap=html.Element('div',{'class':'table-scroll','tabindex':'0','aria-label':title});wrap.append(table);parent.insert(i,wrap)
  for h in frag.xpath('.//*[@id]'):h.set('id',id+'-'+h.get('id'))
  rendered=''.join(etree.tostring(x,encoding='unicode',method='html') for x in frag)
  blocks.append(f'<details class="manual-chapter" id="{id}"'+(' open' if id=='onboarding' else '')+f'><summary>{esc(title)}<span>{len(nums)} 组说明</span></summary><div class="manual-body">{rendered}</div></details>')
  audit['recovered_sections']+=nums
 # Module entrypoints come from the prior full navigation, rather than a newly invented list.
 old=subprocess.check_output(['git','show','0e410f7f1:TEAM_AI_NATIVE_COLLABORATION_GUIDE.html'],cwd=ROOT,text=True)
 old=html.fromstring(old);cards=[]
 aliases={'AI_PRACTICE_SHARING.html#practice-020':'#project-intake','AI_PRACTICE_SHARING.html#practice-024':'#demo-access','AI_PRACTICE_SHARING.html#practice-001':'#parallel'}
 for a in old.xpath('//*[@id="module-grid"]/a'):
  href=aliases.get(a.get('href'),a.get('href'));title=''.join(a.xpath('.//h3/text()'));desc=''.join(a.xpath('.//p/text()'))
  # Counts in the old PM guide were a historical snapshot, not today's directory size.
  if title=='PM Skills 团队指南':desc='按产品经理工作场景查看方法、触发方式与完整说明。'
  if title=='团队魔法：灵犀建项':desc='从来源核对、项目查重开始，整理项目文档；在线登记仍受调用者权限和回查结果约束。'
  attr=' data-team-guide-link="true" target="_blank" rel="noopener"' if href.startswith(BASE) else ''
  cards.append(f'<a class="resource-card" href="{esc(href,quote=True)}"{attr}><h3>{esc(title)}</h3><p>{esc(desc)}</p><span>进入 →</span></a>')
  if href.startswith(BASE):audit['links'].append(href)
 audit['module_count']=len(cards)
 modules='<section id="modules"><h2>原有模块入口，集中在这里</h2><p class="intro">按当前任务进入对应模块。资料说明在本页继续展开；有权限要求的系统仍使用本人的账号。</p><div class="resource-grid">'+''.join(cards)+'</div></section>'
 # Current tracked skill names replace the outdated 172-entry snapshot without losing access.
 paths=subprocess.check_output(['git','-c','core.quotepath=false','ls-files','standards-stack/agent-skills/skills/*/SKILL.md'],cwd=ROOT,text=True).splitlines()
 items=[]
 for path in paths:
  name=Path(path).parent.name;url=BASE+path
  aliases=' '.join(label for keys,label in [('weekly report','周报 汇报'),('supplier pricing','采购 报价'),('manual','手册'),('requirement prd use-case','需求'),('product','产品'),('delivery','交付'),('knowledge wiki','知识'),('video','视频'),('canteen zhct','食堂'),('incident debug troubleshoot','故障 排查'),('database sql dameng','数据库'),('design prototype ui','设计 原型'),('workflow','流程'),('security safety','安全')] if any(key in name for key in keys.split()))
  skill_label = esc(name + ' ' + aliases)
  items.append(f'<li data-skill="{skill_label}"><a href="{esc(url)}" data-team-guide-link="true" target="_blank" rel="noopener">{esc(name)}</a></li>')
  audit['links'].append(url)
 audit['skill_count']=len(items)
 catalog=f'<section id="skill-directory"><h2>完整方法目录：{len(items)} 项</h2><p>Skill 可以理解为可重复使用的工作方法。不用背名称：先说明任务，AI按项目规则选择；需要查具体方法时，在这里搜索名称。</p><label class="search-label" for="skill-search">按名称查找</label><input type="search" id="skill-search" placeholder="例如：周报 weekly、手册 manual、采购 supplier"><p id="skill-status" role="status">显示 {len(items)} 项</p><div class="skill-directory"><ul id="skill-list">'+''.join(items)+'</ul></div></section>'
 audit['links']=sorted(set(audit['links']));audit['replacement_for_historical_section_15']='current tracked skill directory'
 (ROOT/'work/2026-09-26-ai-enablement-refresh/team-restoration-audit.json').write_text(json.dumps(audit,ensure_ascii=False,indent=2)+'\n')
 toc='<nav class="manual-toc" aria-label="完整协作手册目录">'+''.join(f'<a href="#{id}">{esc(title)}</a>' for id,title,_ in groups)+'<a href="#skill-directory">完整方法目录</a></nav>'
 return modules+'<p class="copy-note">完整维护原文：<a data-team-guide-link="true" href="'+BASE+SOURCE+'" target="_blank" rel="noopener">团队成员操作说明</a>。历史案例有各自日期；实时权限、部署状态和业务规则按实际任务复核。</p><section id="manual"><h2>完整操作说明</h2><p class="intro">原有详细内容恢复在下面。点击目录会直接展开对应章节；可用浏览器查找定位文字。</p>'+toc+''.join(blocks)+'</section>'+catalog
