from __future__ import annotations

import re
from pathlib import Path
from typing import Iterable, Optional, Tuple

from .filesystem import safe_read_text
from .models import PluginMetadata

HEADER_KEYS = {
    "Plugin Name": "name",
    "Plugin URI": "plugin_uri",
    "Description": "description",
    "Version": "version",
    "Author": "author",
    "Author URI": "author_uri",
    "Text Domain": "text_domain",
    "Domain Path": "domain_path",
    "Requires at least": "requires_at_least",
    "Requires PHP": "requires_php",
}


def detect_plugin_metadata(php_files: Iterable[Path]) -> Tuple[PluginMetadata, Optional[Path]]:
    header_pattern = re.compile(r"^(?P<key>[A-Za-z ]+):\s*(?P<value>.+)$")
    for php in php_files:
        snippet = safe_read_text(php, limit=12_000)
        lines = snippet.splitlines()
        if len(lines) < 2:
            continue
        meta = PluginMetadata()
        found = False
        for line in lines[:120]:
            m = header_pattern.match(line.strip("/*# \t"))
            if not m:
                continue
            key = m.group("key").strip()
            value = m.group("value").strip()
            if key in HEADER_KEYS:
                setattr(meta, HEADER_KEYS[key], value)
                found = True
        if found and meta.name:
            return meta, php
    return PluginMetadata(), None
