"""Scan leftover generated apps for contact-form notify addresses.

Used by the fleet primitive migrator. Not embedded in the Actions runner.
"""
from __future__ import annotations

import json
import os
from pathlib import Path

from src.domain.feature_packs.config import union_notify_emails
from src.domain.feature_packs.notify_emails import notify_emails_from_text

_SKIP = {
    ".git",
    ".p2hs",
    "node_modules",
    ".nuxt",
    ".output",
    ".next",
    "dist",
    "build",
    "coverage",
    ".venv",
    "venv",
    "__pycache__",
    "tests",
    "__tests__",
}

_CONTACT_NAME_HINTS = (
    "contact",
    "form",
    "admin",
    "be-admin",
    "inbox",
    "mail",
    "notify",
)
_TEXT_SUFFIXES = {".js", ".ts", ".mjs", ".cjs", ".jsx", ".tsx", ".vue", ".html", ".htm", ".json"}


def scan_leftover_notify_emails(repo_path: str) -> str:
    """Collect notify addresses from leftover contact/admin sources."""
    root = Path(repo_path)
    found: list[str] = []
    if not root.is_dir():
        return ""
    for directory, dirs, files in os.walk(root, followlinks=False):
        dir_path = Path(directory)
        dirs[:] = [d for d in dirs if d not in _SKIP and not (dir_path / d).is_symlink()]
        for name in files:
            path = dir_path / name
            if path.suffix.lower() not in _TEXT_SUFFIXES:
                continue
            if name.endswith(".p2hs-local.bak") or name == "p2hs-codegen-action-runner.mjs":
                continue
            try:
                text = path.read_text(encoding="utf-8-sig")
            except (OSError, UnicodeDecodeError):
                continue
            if "p2hs-contact" in text or "p2hs-auth-magic" in text:
                continue
            hinted = notify_emails_from_text(text)
            if hinted:
                found.append(hinted)
                continue
            rel = path.relative_to(root).as_posix().lower()
            if any(token in rel or token in name.lower() for token in _CONTACT_NAME_HINTS):
                found.append(notify_emails_from_text("notify " + text))
    return union_notify_emails(*found)


def contact_capture_config_from_repo(repo_path: str) -> dict:
    path = Path(repo_path) / "p2hs" / "feature-packs.json"
    if not path.is_file():
        return {}
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError, UnicodeDecodeError):
        return {}
    if not isinstance(data, dict):
        return {}
    for row in data.get("install") or []:
        if isinstance(row, dict) and row.get("pack_slug") == "contact-capture":
            cfg = row.get("config")
            return dict(cfg) if isinstance(cfg, dict) else {}
    return {}
