#!/usr/bin/env python3
"""
Implementation Verification for productivity-tracker
Checks for incomplete implementations and missing requirements

Generated by KEN-MCP
Original Requirements: A comprehensive time tracking MCP that helps users log work sessions, categorize activities, generate reports, and analyze productivity patterns. It should track task duration, project categories, and provide insights like daily/weekly summaries.
"""

import os
import re
import sys
import ast
from pathlib import Path
from typing import List, Tuple, Set


class ImplementationVerifier:
    """Verifies that the MCP implementation is complete"""
    
    def __init__(self, project_dir_name: str):
        self.project_dir = Path(__file__).parent.parent / project_dir_name
        self.issues = []
        self.warnings = []
        self.checked_files = []
        
        # Patterns that indicate incomplete implementation
        self.todo_patterns = [
            r'TODO:', r'FIXME:', r'XXX:', r'HACK:', r'NOTE:',
            r'TODO\s*\(', r'FIXME\s*\(', r'XXX\s*\('
        ]
        
        self.placeholder_patterns = [
            r'\bmock\b', r'\bdummy\b', r'\btest[_-]data\b', 
            r'\bplaceholder\b', r'\bexample[_-]\w+\b', 
            r'\bsample[_-]\w+\b', r'\bfake[_-]\w+\b'
        ]
        
        self.hardcoded_patterns = [
            r'generated-id', r'test-\d+', r'id-\d+',
            r'"123"', r"'123'", r'return\s*{}', r'return\s*\[\]'
        ]
        
        self.not_implemented_patterns = [
            r'not[_\s]implemented', r'raise\s+NotImplementedError',
            r'pass\s*$', r'\.\.\.', r'# Implementation goes here'
        ]
        
    def check_file(self, filepath: Path) -> List[Tuple[int, str, str]]:
        """Check a single file for issues"""
        issues = []
        
        try:
            content = filepath.read_text()
            lines = content.splitlines()
            
            for line_num, line in enumerate(lines, 1):
                # Check for TODOs
                for pattern in self.todo_patterns:
                    if re.search(pattern, line, re.IGNORECASE):
                        issues.append((line_num, "TODO", f"Found TODO marker: {line.strip()}"))
                
                # Check for placeholders
                for pattern in self.placeholder_patterns:
                    if re.search(pattern, line, re.IGNORECASE):
                        issues.append((line_num, "PLACEHOLDER", f"Found placeholder: {line.strip()}"))
                
                # Check for hardcoded values
                for pattern in self.hardcoded_patterns:
                    if re.search(pattern, line):
                        issues.append((line_num, "HARDCODED", f"Found hardcoded value: {line.strip()}"))
                
                # Check for not implemented
                for pattern in self.not_implemented_patterns:
                    if re.search(pattern, line, re.IGNORECASE):
                        issues.append((line_num, "NOT_IMPL", f"Not implemented: {line.strip()}"))
                        
        except Exception as e:
            issues.append((0, "ERROR", f"Failed to check file: {e}"))
            
        return issues
    
    def check_ast_implementation(self, filepath: Path) -> List[Tuple[int, str, str]]:
        """Use AST to find empty implementations"""
        issues = []
        
        try:
            content = filepath.read_text()
            tree = ast.parse(content)
            
            for node in ast.walk(tree):
                # Check for functions that only return empty dict/list
                if isinstance(node, ast.FunctionDef):
                    if len(node.body) == 1 and isinstance(node.body[0], ast.Return):
                        return_val = node.body[0].value
                        if isinstance(return_val, (ast.Dict, ast.List)) and not return_val.keys:
                            issues.append((
                                node.lineno, 
                                "EMPTY_IMPL", 
                                f"Function '{node.name}' returns empty container"
                            ))
                            
        except Exception:
            # AST parsing might fail for various reasons, that's OK
            pass
            
        return issues
    
    def check_resources(self) -> List[str]:
        """Check for missing required resources"""
        missing = []
        
        # Check server.py for path references
        server_file = self.project_dir / "server.py"
        if server_file.exists():
            content = server_file.read_text()
            
            # Look for directory creation patterns
            dir_patterns = [
                r"Path\([\"']([^\"']+)[\"']\)",
                r"mkdir\([\"']([^\"']+)[\"']\)",
                r"\.home\(\)\s*/\s*[\"']([^\"']+)[\"']"
            ]
            
            for pattern in dir_patterns:
                matches = re.findall(pattern, content)
                for match in matches:
                    path = Path(match)
                    if not path.exists() and not any(p in str(path) for p in ['~', '$', '{']):
                        missing.append(f"Directory not found: {match}")
                        
            # Check for environment variables
            env_pattern = r"os\.environ\.get\([\"']([^\"']+)[\"']\)"
            env_matches = re.findall(env_pattern, content)
            for env_var in env_matches:
                if env_var not in os.environ:
                    missing.append(f"Environment variable not set: {env_var}")
                    
        return missing
    
    def verify_all(self):
        """Run all verification checks"""
        print("🔍 Implementation Verification for productivity-tracker")
        print("=" * 70)
        
        # Check server.py in project directory
        server_file = self.project_dir / "server.py"
        if not server_file.exists():
            print(f"❌ ERROR: server.py not found in {self.project_dir}!")
            return
            
        print(f"\\nChecking {server_file} for incomplete implementations...")
        print("-" * 70)
        
        # Regular pattern checks
        issues = self.check_file(server_file)
        
        # AST-based checks
        ast_issues = self.check_ast_implementation(server_file)
        issues.extend(ast_issues)
        
        # Resource checks
        missing_resources = self.check_resources()
        
        # Display results
        if not issues and not missing_resources:
            print("\\n✅ No implementation issues found!")
            print("\\nYour MCP appears to be fully implemented.")
        else:
            if issues:
                print(f"\\n⚠️  Found {len(issues)} implementation issue(s):\\n")
                
                # Group by type
                by_type = {}
                for line_num, issue_type, description in issues:
                    if issue_type not in by_type:
                        by_type[issue_type] = []
                    by_type[issue_type].append((line_num, description))
                
                for issue_type, items in by_type.items():
                    print(f"\\n{issue_type} Issues:")
                    for line_num, desc in items:
                        print(f"  Line {line_num}: {desc}")
                        
            if missing_resources:
                print(f"\\n⚠️  Missing Resources:\\n")
                for resource in missing_resources:
                    print(f"  - {resource}")
                    
            print("\\n" + "=" * 70)
            print("📋 REQUIRED ACTIONS:")
            print("=" * 70)
            
            if "TODO" in by_type or "FIXME" in by_type:
                print("\\n1. Address all TODO/FIXME comments in server.py")
                
            if "PLACEHOLDER" in by_type or "HARDCODED" in by_type:
                print("\\n2. Replace placeholder/mock data with real implementations:")
                print("   - Use actual data storage (files, database, etc.)")
                print("   - Generate real IDs (uuid, timestamp-based, etc.)")
                print("   - Implement actual business logic")
                
            if "NOT_IMPL" in by_type or "EMPTY_IMPL" in by_type:
                print("\\n3. Implement empty function bodies:")
                print("   - Add the core functionality described in docstrings")
                print("   - Handle edge cases and errors properly")
                print("   - Return meaningful data, not empty containers")
                
            if missing_resources:
                print("\\n4. Create missing resources:")
                for resource in missing_resources:
                    if "Directory" in resource:
                        print(f"   - Create directory: {resource.split(': ')[1]}")
                    elif "Environment" in resource:
                        print(f"   - Set environment variable: {resource.split(': ')[1]}")
                        
            print("\\n5. After fixing, run tests again: python scripts/test.py")
            print("\\n6. Then run this verification again: python scripts/verify.py")
        
        print("\\n" + "=" * 70)
        
        # Return exit code
        if issues or missing_resources:
            sys.exit(1)
        else:
            sys.exit(0)


if __name__ == "__main__":
    verifier = ImplementationVerifier("productivity-tracker")
    verifier.verify_all()
