#!/usr/bin/env python3
from __future__ import annotations

from collections import defaultdict
import os
from pathlib import Path
import re

ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "languages" / "prorank-seo.pot"
DOMAIN = "prorank-seo"
EXTENSIONS = {".php", ".js", ".jsx", ".ts", ".tsx"}
SKIP_PARTS = {"node_modules", "vendor", "build", "wporg-assets", "languages", ".git"}


def escape(value: str) -> str:
    return value.replace("\\", "\\\\").replace('"', '\\"')


SIMPLE_PATTERNS = [
    re.compile(r"""(?:__|_e|esc_html__|esc_attr__)\(\s*['"]([^'"]+)['"]\s*,\s*['"]prorank-seo['"]"""),
]
CONTEXT_PATTERNS = [
    re.compile(r"""(?:_x|_ex|esc_html_x|esc_attr_x)\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]\s*,\s*['"]prorank-seo['"]"""),
]
PLURAL_PATTERNS = [
    re.compile(r"""_n\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]\s*,.+?,\s*['"]prorank-seo['"]"""),
    re.compile(r"""_nx\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]\s*,.+?,\s*['"]([^'"]+)['"]\s*,\s*['"]prorank-seo['"]"""),
]


entries: dict[tuple[str, str | None, str | None], set[str]] = defaultdict(set)

for root, dirnames, filenames in os.walk(ROOT, topdown=True):
    dirnames[:] = [dirname for dirname in dirnames if dirname not in SKIP_PARTS]
    root_path = Path(root)

    for filename in filenames:
        path = root_path / filename
        if path.suffix not in EXTENSIONS:
            continue

        rel = path.relative_to(ROOT).as_posix()
        for lineno, line in enumerate(path.read_text(encoding="utf-8", errors="ignore").splitlines(), start=1):
            for pattern in SIMPLE_PATTERNS:
                for match in pattern.finditer(line):
                    entries[(match.group(1), None, None)].add(f"{rel}:{lineno}")

            for pattern in CONTEXT_PATTERNS:
                for match in pattern.finditer(line):
                    entries[(match.group(1), match.group(2), None)].add(f"{rel}:{lineno}")

            for pattern in PLURAL_PATTERNS:
                for match in pattern.finditer(line):
                    if len(match.groups()) == 2:
                        entries[(match.group(1), None, match.group(2))].add(f"{rel}:{lineno}")
                    else:
                        entries[(match.group(1), match.group(3), match.group(2))].add(f"{rel}:{lineno}")


header = f'''msgid ""
msgstr ""
"Project-Id-Version: ProRank SEO 1.0.0\\n"
"Report-Msgid-Bugs-To: https://prorank.io/support\\n"
"POT-Creation-Date: 2026-03-07 00:00+0000\\n"
"MIME-Version: 1.0\\n"
"Content-Type: text/plain; charset=UTF-8\\n"
"Content-Transfer-Encoding: 8bit\\n"
"X-Domain: {DOMAIN}\\n"

'''

parts = [header]
for (msgid, context, plural), refs in sorted(entries.items(), key=lambda item: (item[0][1] or "", item[0][0])):
    parts.append("#: " + " ".join(sorted(refs)) + "\n")
    if context:
        parts.append(f'msgctxt "{escape(context)}"\n')
    parts.append(f'msgid "{escape(msgid)}"\n')
    if plural is not None:
        parts.append(f'msgid_plural "{escape(plural)}"\n')
        parts.append('msgstr[0] ""\n')
        parts.append('msgstr[1] ""\n\n')
    else:
        parts.append('msgstr ""\n\n')

OUT.write_text("".join(parts), encoding="utf-8")
print(OUT)
print(f"entries={len(entries)}")
