"""
fix_seo.py — topeduprep.uk Cloudflare Pages SEO 수정 스크립트

실행 방법:
    python fix_seo.py <HTML_파일_경로>

예시:
    python fix_seo.py index.html

생성 파일:
    - index.html (수정본, 원본은 index.html.bak으로 백업)
    - _redirects   (www → non-www 301 리디렉션)
    - robots.txt
    - sitemap.xml
"""

import re
import shutil
import sys
from datetime import date
from pathlib import Path

# ── 설정 ──────────────────────────────────────────────────────────────────────
DOMAIN        = "https://topeduprep.uk"
CANONICAL_URL = f"{DOMAIN}/"
SITEMAP_URL   = f"{DOMAIN}/sitemap.xml"
TODAY         = date.today().isoformat()
# ─────────────────────────────────────────────────────────────────────────────


def fix_html(html_path: Path) -> None:
    """canonical 태그 수정 + robots/sitemap meta 추가"""
    src = html_path.read_text(encoding="utf-8")

    # 1) 백업
    bak = html_path.with_suffix(html_path.suffix + ".bak")
    shutil.copy2(html_path, bak)
    print(f"[백업] {bak}")

    # 2) canonical 수정 (index.html → /)
    canonical_pattern = re.compile(
        r'<link\s[^>]*rel=["\']canonical["\'][^>]*>', re.IGNORECASE
    )
    new_canonical = f'<link rel="canonical" href="{CANONICAL_URL}">'

    if canonical_pattern.search(src):
        src = canonical_pattern.sub(new_canonical, src)
        print("[수정] canonical 태그 업데이트")
    else:
        # <head> 바로 뒤에 삽입
        src = src.replace("<head>", f"<head>\n  {new_canonical}", 1)
        print("[추가] canonical 태그 삽입")

    # 3) robots meta 추가 (없으면)
    robots_meta = '<meta name="robots" content="index, follow">'
    if 'name="robots"' not in src and "name='robots'" not in src:
        src = src.replace(new_canonical, f"{new_canonical}\n  {robots_meta}", 1)
        print("[추가] robots meta 태그 삽입")

    html_path.write_text(src, encoding="utf-8")
    print(f"[완료] {html_path} 저장")


def write_redirects(out_dir: Path) -> None:
    """_redirects — www → non-www 301"""
    content = (
        "# www → non-www 301 리디렉션\n"
        "https://www.topeduprep.uk/*  https://topeduprep.uk/:splat  301\n"
        "\n"
        "# index.html → / (canonical 중복 방지)\n"
        "https://topeduprep.uk/index.html  https://topeduprep.uk/  301\n"
    )
    path = out_dir / "_redirects"
    path.write_text(content, encoding="utf-8")
    print(f"[생성] {path}")


def write_robots(out_dir: Path) -> None:
    """robots.txt"""
    content = (
        "User-agent: *\n"
        "Allow: /\n"
        f"Sitemap: {SITEMAP_URL}\n"
    )
    path = out_dir / "robots.txt"
    path.write_text(content, encoding="utf-8")
    print(f"[생성] {path}")


def write_sitemap(out_dir: Path) -> None:
    """sitemap.xml — 단일 페이지"""
    content = f"""<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>{CANONICAL_URL}</loc>
    <lastmod>{TODAY}</lastmod>
    <changefreq>monthly</changefreq>
    <priority>1.0</priority>
  </url>
</urlset>
"""
    path = out_dir / "sitemap.xml"
    path.write_text(content, encoding="utf-8")
    print(f"[생성] {path}")


def main():
    if len(sys.argv) < 2:
        print("사용법: python fix_seo.py <HTML_파일_경로>")
        print("예시:   python fix_seo.py index.html")
        sys.exit(1)

    html_path = Path(sys.argv[1]).resolve()
    if not html_path.exists():
        print(f"오류: 파일을 찾을 수 없습니다 → {html_path}")
        sys.exit(1)

    out_dir = html_path.parent
    print(f"\n=== SEO 수정 시작 (출력 폴더: {out_dir}) ===\n")

    fix_html(html_path)
    write_redirects(out_dir)
    write_robots(out_dir)
    write_sitemap(out_dir)

    print(f"""
=== 완료 ===

다음 파일들을 Cloudflare Pages 프로젝트 루트에 배포하세요:
  ✅ {html_path.name}   (canonical 수정됨)
  ✅ _redirects         (www 리디렉션)
  ✅ robots.txt
  ✅ sitemap.xml

배포 후 Google Search Console에서:
  1. URL 검사 → https://topeduprep.uk/ → 색인 생성 요청
  2. 사이트맵 제출 → {SITEMAP_URL}
""")


if __name__ == "__main__":
    main()
