#!/usr/bin/env python3
"""
Artifact Manager Hook
Implements Reference-Based Communication from Claude Collective v9.4.2

Manages artifact persistence and ensures any data exceeding 50 tokens
is persisted by HELIOS and shared via reference handles (@artifact:version).
"""

import hashlib
import json
import sys
import time
from pathlib import Path


def count_tokens_estimate(text: str) -> int:
    """Rough estimate of token count (1 token ≈ 4 characters)."""
    return len(text) // 4


def generate_artifact_reference(file_path: str, content_hash: str) -> str:
    """Generate a reference handle for the artifact."""
    filename = Path(file_path).stem
    timestamp = int(time.time())
    return f"@{filename}:{content_hash[:8]}:{timestamp}"


def update_state_manifest(
    artifact_ref: str, file_path: str, description: str = ""
) -> None:
    """Update the STATE_MANIFEST.md with the new artifact."""
    manifest_path = Path("artifacts/STATE_MANIFEST.md")
    manifest_path.parent.mkdir(exist_ok=True)

    # Create or read existing manifest
    if manifest_path.exists():
        with open(manifest_path, "r", encoding="utf-8") as f:
            content = f.read()
    else:
        content = "# State Manifest\n\n## Active Artifacts\n\n"

    # Add new artifact entry
    entry = f"- **{artifact_ref}**: `{file_path}` - {description}\n"

    if "## Active Artifacts" in content:
        content = content.replace(
            "## Active Artifacts\n\n", f"## Active Artifacts\n\n{entry}"
        )
    else:
        content += f"\n## Active Artifacts\n\n{entry}"

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


def archive_large_artifacts(file_path: str, content: str) -> tuple[str, str]:
    """Archive artifacts that exceed the token limit."""
    artifacts_dir = Path("artifacts/")
    artifacts_dir.mkdir(exist_ok=True)

    # Generate content hash for versioning
    content_hash = hashlib.sha256(content.encode()).hexdigest()

    # Create artifact reference
    artifact_ref = generate_artifact_reference(file_path, content_hash)

    # Archive the content
    archive_filename = f"{Path(file_path).stem}_{content_hash[:8]}.md"
    archive_path = artifacts_dir / archive_filename

    with open(archive_path, "w", encoding="utf-8") as f:
        f.write(f"# Artifact: {artifact_ref}\n\n")
        f.write(f"**Source**: {file_path}\n")
        f.write(f"**Created**: {time.strftime('%Y-%m-%d %H:%M:%S')}\n\n")
        f.write("## Content\n\n")
        f.write(content)

    # Update state manifest
    update_state_manifest(artifact_ref, str(archive_path), f"Archived from {file_path}")

    return artifact_ref, str(archive_path)


def main() -> None:
    try:
        input_data = json.load(sys.stdin)
    except json.JSONDecodeError as e:
        print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
        sys.exit(1)

    tool_input = input_data.get("tool_input", {})

    file_path = tool_input.get("file_path", "")
    content = tool_input.get("content", "")

    if not file_path or not content:
        sys.exit(0)

    # Skip certain files from artifact management
    skip_patterns = [
        ".git/",
        "node_modules/",
        "__pycache__/",
        ".env",
        "package-lock.json",
    ]
    if any(pattern in file_path for pattern in skip_patterns):
        sys.exit(0)

    # Check if content exceeds 50 token threshold
    token_count = count_tokens_estimate(content)

    if token_count > 50:
        print(f"📦 HELIOS: Archiving artifact {file_path} ({token_count} tokens)")

        try:
            artifact_ref, archive_path = archive_large_artifacts(file_path, content)

            # Provide feedback with reference handle
            output = {
                "continue": True,
                "reason": f"Artifact archived as {artifact_ref}. \
                Reference this artifact using {artifact_ref} in future communications.",
            }
            print(json.dumps(output))

            print(f"✅ HELIOS: Artifact {artifact_ref} archived to {archive_path}")

        except Exception as e:
            print(f"❌ HELIOS: Failed to archive artifact: {e}", file=sys.stderr)
            sys.exit(1)

    sys.exit(0)


if __name__ == "__main__":
    main()
