#!/usr/bin/env python3
"""
[废弃] 扫描 HTML 引用并重写为 CDN 绝对地址

原本为解决 /api/file 加载时相对路径失效的问题而设计。
现状：模板预览已改为直接从 CDN 加载，相对路径天然可用，重写无必要。
"""

import re
from pathlib import Path
from typing import Dict, Optional, Set
from urllib.parse import urlparse, unquote

from qiniu import Auth, put_file_v2, CdnManager

QINIU_KEY    = "T3tgxM7EMx1j4VESw4m4PIfFXoOvBo-wQEOQewXX"
QINIU_SECRET = "PVZvlKVOjX2RqlV2ILMg-QwpNMssOlpVbaEzypz0"
QINIU_BUCKET = "yiran1"
CDN_DOMAIN   = "https://cdn.yiranlaoshi.com"
CDN_PREFIX   = "myclaw/live/yiran/skills/yiran-playground-template-use/templates"

q           = Auth(QINIU_KEY, QINIU_SECRET)
cdn_manager = CdnManager(q)

ATTR_RE = re.compile(r'(src|href)=["\']([^"\']+)["\']', re.IGNORECASE)
URL_RE  = re.compile(r'url\(["\']?([^)"\']+)["\']?\)', re.IGNORECASE)
SKIP_PREFIXES = ('data:', '#', 'mailto:', 'javascript:')


def is_external(url):
    return url.startswith('http://') or url.startswith('https://') or url.startswith('//')


def find_local_file(ref, base_dir):
    if any(ref.startswith(p) for p in SKIP_PREFIXES):
        return None
    if is_external(ref):
        filename = Path(unquote(urlparse(ref).path)).name
        candidate = base_dir / filename
        return candidate if candidate.is_file() else None
    else:
        candidate = (base_dir / ref).resolve()
        if candidate.is_file() and str(candidate).startswith(str(base_dir.resolve())):
            return candidate
        return None


def collect_refs(html):
    refs = set()
    for m in ATTR_RE.finditer(html):
        refs.add(m.group(2))
    for m in URL_RE.finditer(html):
        refs.add(m.group(1))
    return refs


def rewrite_html(html, ref_map):
    def replace_attr(m):
        attr, val = m.group(1), m.group(2)
        return '{}="{}"'.format(attr, ref_map.get(val, val))
    def replace_url(m):
        val = m.group(1)
        return 'url("{}")'.format(ref_map.get(val, val))
    html = ATTR_RE.sub(replace_attr, html)
    html = URL_RE.sub(replace_url, html)
    return html


def upload_file(local_path, folder_name):
    key = "{}/{}/{}".format(CDN_PREFIX, folder_name, local_path.name)
    token = q.upload_token(QINIU_BUCKET, key, 3600, policy={'insertOnly': 0})
    ret, info = put_file_v2(token, key, str(local_path))
    if info.status_code != 200:
        raise RuntimeError("上传失败 {}: {}".format(local_path.name, info))
    cdn_url = "{}/{}".format(CDN_DOMAIN, key)
    cdn_manager.refresh_urls([cdn_url])
    return cdn_url


def rewrite_and_upload(folder_path):
    folder_name = folder_path.name
    html_files  = list(folder_path.glob('*.html'))
    uploaded = {}
    all_refs = {}

    for html_file in html_files:
        html = html_file.read_text(encoding='utf-8')
        for ref in collect_refs(html):
            if ref in all_refs:
                continue
            local = find_local_file(ref, folder_path)
            if local:
                if local not in uploaded:
                    cdn_url = upload_file(local, folder_name)
                    uploaded[local] = cdn_url
                all_refs[ref] = uploaded[local]

    for html_file in html_files:
        html = html_file.read_text(encoding='utf-8')
        new_html = rewrite_html(html, all_refs)
        html_file.write_text(new_html, encoding='utf-8')
        upload_file(html_file, folder_name)
