#!/usr/bin/env python3
# Familiar - Self-Hosted AI Companion Platform
# Copyright (c) 2026 George Scott Foley
# ORCID: 0009-0006-4957-0540
# Email: Georgescottfoley@proton.me
# Licensed under the MIT License - see LICENSE file for details

"""
Add MIT license headers to all Familiar source files.
Run from familiar root directory.
"""

import os

PYTHON_HEADER = """# Familiar - Self-hosted AI Agent
# Copyright (c) 2026 George Scott Foley
#
# Licensed under the MIT License - see LICENSE file for details;
#
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# For commercial licensing, contact: licensing@familiar.ai

"""

JS_HEADER = """/**
 * Familiar - Self-hosted AI Agent
 * Copyright (c) 2026 George Scott Foley
 *
 * Licensed under the MIT License - see LICENSE file for details;
 *
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * For commercial licensing, contact: licensing@familiar.ai
 */

"""

CSS_HEADER = """/**
 * Familiar - Self-hosted AI Agent
 * Copyright (c) 2026 George Scott Foley
 *
 * Licensed under the MIT License - see LICENSE file for details
 * For commercial licensing, contact: licensing@familiar.ai
 */

"""

HTML_HEADER = """<!--
  Familiar - Self-hosted AI Agent
  Copyright (c) 2026 George Scott Foley

  Licensed under the MIT License - see LICENSE file for details
  For commercial licensing, contact: licensing@familiar.ai
-->
"""

SKIP_DIRS = {".git", "__pycache__", ".pytest_cache", "node_modules", ".venv", "venv"}
SKIP_FILES = {"__init__.py"}  # Handle these separately if needed


def has_license_header(content):
    """Check if file already has a license header."""
    lower = content[:500].lower()
    return "license" in lower and ("business source" in lower or "copyright" in lower)


def add_header_to_python(filepath):
    """Add header to Python file."""
    with open(filepath, "r", encoding="utf-8", errors="ignore") as f:
        content = f.read()

    if has_license_header(content):
        return False

    # Handle shebang
    if content.startswith("#!"):
        lines = content.split("\n", 1)
        new_content = lines[0] + "\n" + PYTHON_HEADER + lines[1]
    else:
        new_content = PYTHON_HEADER + content

    with open(filepath, "w", encoding="utf-8") as f:
        f.write(new_content)

    return True


def add_header_to_js(filepath):
    """Add header to JavaScript file."""
    with open(filepath, "r", encoding="utf-8", errors="ignore") as f:
        content = f.read()

    if has_license_header(content):
        return False

    new_content = JS_HEADER + content

    with open(filepath, "w", encoding="utf-8") as f:
        f.write(new_content)

    return True


def add_header_to_css(filepath):
    """Add header to CSS file."""
    with open(filepath, "r", encoding="utf-8", errors="ignore") as f:
        content = f.read()

    if has_license_header(content):
        return False

    new_content = CSS_HEADER + content

    with open(filepath, "w", encoding="utf-8") as f:
        f.write(new_content)

    return True


def add_header_to_html(filepath):
    """Add header to HTML file."""
    with open(filepath, "r", encoding="utf-8", errors="ignore") as f:
        content = f.read()

    if has_license_header(content):
        return False

    # Handle doctype
    if content.lower().startswith("<!doctype"):
        lines = content.split("\n", 1)
        new_content = lines[0] + "\n" + HTML_HEADER + lines[1]
    else:
        new_content = HTML_HEADER + content

    with open(filepath, "w", encoding="utf-8") as f:
        f.write(new_content)

    return True


def process_directory(root_dir):
    """Process all files in directory."""
    stats = {"python": 0, "js": 0, "css": 0, "html": 0, "skipped": 0}

    for dirpath, dirnames, filenames in os.walk(root_dir):
        # Skip excluded directories
        dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]

        for filename in filenames:
            filepath = os.path.join(dirpath, filename)

            try:
                if filename.endswith(".py"):
                    if add_header_to_python(filepath):
                        stats["python"] += 1
                        print(f"  ✓ {filepath}")
                    else:
                        stats["skipped"] += 1

                elif filename.endswith(".js"):
                    if add_header_to_js(filepath):
                        stats["js"] += 1
                        print(f"  ✓ {filepath}")
                    else:
                        stats["skipped"] += 1

                elif filename.endswith(".css"):
                    if add_header_to_css(filepath):
                        stats["css"] += 1
                        print(f"  ✓ {filepath}")
                    else:
                        stats["skipped"] += 1

                elif filename.endswith(".html"):
                    if add_header_to_html(filepath):
                        stats["html"] += 1
                        print(f"  ✓ {filepath}")
                    else:
                        stats["skipped"] += 1

            except Exception as e:
                print(f"  ✗ Error processing {filepath}: {e}")

    return stats


def main():
    root_dir = os.path.dirname(os.path.abspath(__file__))

    print("=" * 60)
    print("Familiar License Header Addition")
    print("=" * 60)
    print(f"\nProcessing: {root_dir}\n")

    stats = process_directory(root_dir)

    print("\n" + "=" * 60)
    print("Summary")
    print("=" * 60)
    print(f"  Python files updated: {stats['python']}")
    print(f"  JavaScript files updated: {stats['js']}")
    print(f"  CSS files updated: {stats['css']}")
    print(f"  HTML files updated: {stats['html']}")
    print(f"  Already had headers: {stats['skipped']}")
    print(f"\n  Total updated: {stats['python'] + stats['js'] + stats['css'] + stats['html']}")
    print("=" * 60)


if __name__ == "__main__":
    main()
