import os
from datetime import datetime
from pathlib import Path


def merge_dir(content_blocks, directory, section_title, base, flat=False):
    if not directory.exists():
        return
    content_blocks.append(f"## {section_title}\n")
    if flat:
        for file_path in sorted(directory.rglob("*")):
            if not file_path.is_file():
                continue
            relative = file_path.relative_to(base)
            try:
                content = file_path.read_text(encoding="utf-8")
            except Exception as e:
                print(f"Skipping {file_path}: {e}")
                continue
            content_blocks.append(f"### {relative}\n")
            content_blocks.append(content)
            content_blocks.append("\n")
    else:
        for sub_dir in sorted(directory.iterdir()):
            if not sub_dir.is_dir():
                continue
            for file_path in sorted(sub_dir.rglob("*")):
                if not file_path.is_file():
                    continue
                relative = file_path.relative_to(base)
                try:
                    content = file_path.read_text(encoding="utf-8")
                except Exception as e:
                    print(f"Skipping {file_path}: {e}")
                    continue
                content_blocks.append(f"### {relative}\n")
                content_blocks.append(content)
                content_blocks.append("\n")


def merge_kilo():
    skills_dir = Path(".kilo/skills")
    agents_dir = Path(".kilo/agents")
    workflows_dir = Path(".kilocode/workflows")

    root = Path(".")
    if not (skills_dir.exists() or agents_dir.exists() or workflows_dir.exists()):
        print("Error: No source directories found.")
        return

    now = datetime.now().strftime("%Y%m%d-%H%M%S")
    output_filename = f"kilo-merged-{now}.md"

    content_blocks = ["# Kilo Configuration Snapshot\n"]

    merge_dir(content_blocks, skills_dir, "Skills", root, flat=False)
    merge_dir(content_blocks, agents_dir, "Agents", root, flat=True)
    merge_dir(content_blocks, workflows_dir, "Workflows", root, flat=True)

    with open(output_filename, "w", encoding="utf-8") as f:
        f.write("\n".join(content_blocks))

    print(f"Successfully created: {output_filename}")


if __name__ == "__main__":
    merge_kilo()
