"""Nothing P2HS owns may reach a customer-owned repository (GitHub, GitLab, Bitbucket,
Azure DevOps all share _overlay_publish_tree / _skip_publish_path).

The old rule set excluded the codegen runner script only because a content scan happened to
find a scanned host name in it, and published any other .github/workflows/*.yml. These tests
use real files with *innocuous* content, so a path rule -- not the leak scan -- must be what
keeps them out.
"""

from __future__ import annotations

import os
import tempfile

from src.domain.codegen import actions_pipeline
from src.domain.codegen.import_snapshot import IMPORT_DIR
from src.domain.codegen.repo_export import (
    PLATFORM_OWNED_FILES,
    PLATFORM_OWNED_TOP_DIRS,
    is_platform_owned_path,
)
from src.workers.tasks.merge_and_deploy import _overlay_publish_tree

APP_FILES = {
    "index.html": "<h1>Site</h1>",
    "css/site.css": "body { margin: 0 }",
    "js/app.js": "console.log('hi')",
    "public/logo.png": "png",
    "package.json": "{}",
}

PLATFORM_FILES = {
    # the dispatch commit (actions_pipeline.dispatch_codegen_actions_run)
    actions_pipeline.RUNNER_PATH: "// runner",
    actions_pipeline.WORKFLOW_PATH: "name: x",
    f"{actions_pipeline.PAYLOAD_DIR}/run-1.json": "{}",
    ".p2hs-user-uploads/run-1/manifest.json": "{}",
    ".p2hs-user-uploads/run-1/photo.png": "png",
    # imported-source snapshot (import_snapshot.py)
    f"{IMPORT_DIR}/abc/manifest.json": "{}",
    f"{IMPORT_DIR}/abc/files/index.html": "<h1>Original</h1>",
    f"{IMPORT_DIR}/abc/files/js/app.js": "console.log('original')",
    # other platform-owned material
    ".p2hs-control/state.json": "{}",
    "p2hs/feature-packs.json": "{}",
    "p2hs/prompt-media/run-1/a.png": "png",
    ".github/workflows/deploy.yml": "name: deploy",
    ".github/workflows/p2hs-codegen.yml": "name: codegen",
    ".github/workflows/p2hs-anything-new.yml": "name: future p2hs workflow",
    "CLAUDE.md": "# notes",
    "AGENTS.md": "# notes",
    "p2hs.platform.json": "{}",
}


def _write_tree(root: str, files: dict[str, str]) -> None:
    for relative, content in files.items():
        path = os.path.join(root, *relative.split("/"))
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, "w", encoding="utf-8") as handle:
            handle.write(content)


def _published(files: dict[str, str]) -> set[str]:
    with tempfile.TemporaryDirectory() as source, tempfile.TemporaryDirectory() as destination:
        _write_tree(source, files)
        _overlay_publish_tree(source, destination)
        found = set()
        for root, _dirs, names in os.walk(destination):
            for name in names:
                found.add(os.path.relpath(os.path.join(root, name), destination).replace("\\", "/"))
        return found


def test_no_platform_owned_file_reaches_a_customer_repo():
    published = _published({**APP_FILES, **PLATFORM_FILES})
    leaked = sorted(published & set(PLATFORM_FILES))
    assert leaked == []


def test_the_app_itself_is_still_published():
    published = _published({**APP_FILES, **PLATFORM_FILES})
    assert set(APP_FILES) <= published


def test_platform_paths_are_excluded_by_path_alone_not_by_the_content_scan():
    """Content is deliberately innocuous above; also check the rule directly."""
    for relative in PLATFORM_FILES:
        assert is_platform_owned_path(relative.split("/")), relative
    for relative in APP_FILES:
        assert not is_platform_owned_path(relative.split("/")), relative


def test_the_exclusion_list_cannot_drift_from_what_the_dispatch_commits():
    assert actions_pipeline.RUNNER_PATH.lower() in PLATFORM_OWNED_FILES
    assert actions_pipeline.WORKFLOW_PATH.lower() in PLATFORM_OWNED_FILES
    assert actions_pipeline.PAYLOAD_DIR.split("/")[0] in PLATFORM_OWNED_TOP_DIRS
    assert IMPORT_DIR.split("/")[0] in PLATFORM_OWNED_TOP_DIRS
    assert ".p2hs-user-uploads" in PLATFORM_OWNED_TOP_DIRS


def test_case_does_not_bypass_the_exclusion():
    assert is_platform_owned_path([".P2HS", "imports", "x", "files", "a.js"])
    assert is_platform_owned_path(["Scripts", "P2hs-Codegen-Action-Runner.mjs"])
    assert is_platform_owned_path([".GitHub", "Workflows", "P2HS-Codegen.yml"])


def test_a_customers_own_similarly_named_files_are_not_swallowed():
    assert not is_platform_owned_path(["src", "p2hs", "client.ts"])
    assert not is_platform_owned_path(["scripts", "build.mjs"])
    assert not is_platform_owned_path([".github", "dependabot.yml"])
