import os
from typing import List, Dict, Any
from xeolint_core.rule import Rule
from xeolint_core.models import AuditResult, FixResult, CheckLevel, FixStatus
from xeolint_core.parsers import NextProjectAnalyzer, MetadataExtractor

class MissingMetaDescriptionRule(Rule):
    @property
    def id(self) -> str:
        return "missing_meta_description"
        
    @property
    def description(self) -> str:
        return "Checks if a meta description is defined. Crucial for search result snippets and AI summaries."
        
    def audit(self, context: Dict[str, Any]) -> List[AuditResult]:
        workspace = context["workspace_path"]
        analyzer = NextProjectAnalyzer(workspace)
        page_files = analyzer.get_all_page_files()
        
        results = []
        
        for file_path in page_files:
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                    
                is_app_router = "app" in file_path.split(os.sep)
                
                if is_app_router:
                    if MetadataExtractor.has_app_router_metadata(content) and not MetadataExtractor.has_app_router_description(content):
                        results.append(AuditResult(
                            rule_id=self.id,
                            level=CheckLevel.WARNING,
                            message="Metadata exported, but no description defined.",
                            filepath=file_path,
                            fix_suggestion="Add a 'description' key to the exported metadata object."
                        ))
                else:
                    # Very basic check for Pages Router
                    if "<Head>" in content and "name=\"description\"" not in content and "name='description'" not in content:
                         results.append(AuditResult(
                            rule_id=self.id,
                            level=CheckLevel.WARNING,
                            message="No <meta name=\"description\"> found inside <Head>.",
                            filepath=file_path,
                            fix_suggestion="Add <meta name='description' content='...'> inside <Head>."
                        ))
            except Exception:
                pass
                
        return results
