#!/usr/bin/env python3
"""
Copy K8s manifests to Kustomize base directory and remove namespace declarations
"""
import os
import shutil
import yaml
from pathlib import Path

# Service names
SERVICES = [
    'user-service',
    'event-service',
    'ai-service',
    'content-service',
    'distribution-service',
    'participation-service',
    'analytics-service'
]

# Base directories
SOURCE_DIR = Path('deployment/k8s')
BASE_DIR = Path('.github/kustomize/base')

def remove_namespace_from_yaml(content):
    """Remove namespace field from YAML content"""
    docs = list(yaml.safe_load_all(content))

    for doc in docs:
        if doc and isinstance(doc, dict):
            if 'metadata' in doc and 'namespace' in doc['metadata']:
                del doc['metadata']['namespace']

    return yaml.dump_all(docs, default_flow_style=False, sort_keys=False)

def copy_and_process_file(source_path, dest_path):
    """Copy file and remove namespace declaration"""
    with open(source_path, 'r', encoding='utf-8') as f:
        content = f.read()

    # Remove namespace from YAML
    processed_content = remove_namespace_from_yaml(content)

    # Write to destination
    dest_path.parent.mkdir(parents=True, exist_ok=True)
    with open(dest_path, 'w', encoding='utf-8') as f:
        f.write(processed_content)

    print(f"✓ Copied and processed: {source_path} -> {dest_path}")

def main():
    print("Starting manifest copy to Kustomize base...")

    # Copy common resources
    print("\n[Common Resources]")
    common_dir = SOURCE_DIR / 'common'
    for file in ['cm-common.yaml', 'secret-common.yaml', 'secret-imagepull.yaml', 'ingress.yaml']:
        source = common_dir / file
        if source.exists():
            dest = BASE_DIR / file
            copy_and_process_file(source, dest)

    # Copy service-specific resources
    print("\n[Service Resources]")
    for service in SERVICES:
        service_dir = SOURCE_DIR / service
        if not service_dir.exists():
            print(f"⚠ Service directory not found: {service_dir}")
            continue

        print(f"\nProcessing {service}...")
        for file in service_dir.glob('*.yaml'):
            dest = BASE_DIR / f"{service}-{file.name}"
            copy_and_process_file(file, dest)

    print("\n✅ All manifests copied to base directory!")

if __name__ == '__main__':
    main()
