from __future__ import annotations

import argparse
import json
import re
from datetime import datetime, timezone
from pathlib import Path
from uuid import uuid4


def export_html_bundle(html_path, *, title, requirement, receipt_path, output):
    html = Path(html_path).read_text(encoding="utf-8")
    if not 1 <= len(html) <= 500000 or not re.search(r"</html\s*>\s*$", html, re.I):
        raise ValueError("成果必须是完整 HTML，且不超过 500,000 字符")
    if not 1 <= len(title) <= 120:
        raise ValueError("成果标题须为 1–120 字符")
    if not requirement.strip() or len(requirement) > 20000:
        raise ValueError("原始要求须为 1–20,000 字符")
    source = json.loads(Path(receipt_path).read_text(encoding="utf-8")) if receipt_path else {}
    receipt = {key: source[key] for key in (
        "model", "requested_model", "response_models", "channel", "usage", "elapsed_seconds", "request_id",
    ) if key in source}
    bundle = {
        "schema": "harbourmind.studio.delivery.v1", "id": f"terminal_{uuid4().hex}",
        "title": title, "requirement": requirement, "html": html,
        "created_at": datetime.now(timezone.utc).isoformat(), "receipt": receipt,
    }
    target = Path(output).expanduser().resolve()
    target.write_text(json.dumps(bundle, ensure_ascii=False, indent=2), encoding="utf-8")
    print(f"成果包已保存：{target}\n在 Studio 的“配置终端”中导入当前频道。")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="将终端生成的 HTML 导出为 Studio 成果包；只使用 Python 标准库，不调用模型。")
    parser.add_argument("html")
    parser.add_argument("--title", required=True)
    parser.add_argument("--requirement", required=True)
    parser.add_argument("--receipt", help="模型公开回执 JSON")
    parser.add_argument("--output", default="result.hm-studio.json")
    args = parser.parse_args()
    export_html_bundle(args.html, title=args.title, requirement=args.requirement, receipt_path=args.receipt, output=args.output)
