import json
import logging
import threading
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional

from whitemagic.config import PROJECT_ROOT
from .dig import ChariotArchaeologist, Grimoire, Ganas

logger = logging.getLogger("Chariot")

_archaeologist: Optional['ChariotArchaeologist'] = None
_arch_lock = threading.Lock()

def get_archaeologist() -> 'ChariotArchaeologist':
    """Get the global ChariotArchaeologist singleton."""
    global _archaeologist
    if _archaeologist is None:
        with _arch_lock:
            if _archaeologist is None:
                target_dir = str(PROJECT_ROOT)
                output_dir = str(PROJECT_ROOT / "core_system" / "data")
                _archaeologist = ChariotArchaeologist(target_dir, output_dir)
    return _archaeologist

def mark_read(path: str, context: Optional[str] = None, note: Optional[str] = None, insight: Optional[str] = None) -> Dict[str, Any]:
    return get_archaeologist().mark_read(path, context, note, insight)

def mark_written(path: str, context: Optional[str] = None, note: Optional[str] = None) -> Dict[str, Any]:
    return get_archaeologist().mark_written(path, context, note)

def have_read(path: str) -> bool:
    return get_archaeologist().have_read(path)

def find_unread(directory: str = ".", patterns: Optional[List[str]] = None) -> List[Any]:
    return get_archaeologist().find_unread(directory, patterns)

def stats(scan_disk: bool = False) -> Dict[str, Any]:
    return get_archaeologist().stats(scan_disk=scan_disk)

# Bridge for WisdomExtractor (placeholder for now using Chariot logic)
class WisdomExtractor:
    def __init__(self):
        self.arch = get_archaeologist()

    def extract_wisdom(self, content: str, source: str) -> Dict[str, Any]:
        return {
            "chapters": Grimoire.identify(content, source),
            "gana": Ganas.identify(content, source)
        }

def get_wisdom_extractor() -> WisdomExtractor:
    return WisdomExtractor()

def process_wisdom_archives(limit_files: int = 1000, memory_type: str = "long_term") -> Dict[str, Any]:
    """Process files found by Chariot into memories."""
    extractor = get_wisdom_extractor()
    
    # Path to the report file generated by Chariot
    report_file = Path(PROJECT_ROOT) / "core_system" / "data" / "recovered_memories.jsonl"
    if not report_file.exists():
        return {"status": "error", "message": "No recovered_memories.jsonl found. Run Chariot dig first."}
    
    from whitemagic.core.memory.unified import get_unified_memory
    unified = get_unified_memory()
    
    processed = 0
    with open(report_file, "r") as f:
        for line in f:
            if processed >= limit_files:
                break
            try:
                finding = json.loads(line)
                if "meta" in finding:
                    continue
                
                path = Path(finding["path"])
                if not path.exists():
                    continue
                
                content = path.read_text(errors="ignore")
                extractor.extract_wisdom(content, path.name)
                
                # Create memory entry
                tags = ["archaeology", "recovered"]
                if finding.get("anthropology", {}).get("gana"):
                    tags.append(f"gana:{finding['anthropology']['gana']}")
                
                unified.store(
                    content=content,
                    title=f"Recovered: {path.name}",
                    memory_type=memory_type,
                    tags=tags,
                    metadata={
                        "original_path": str(path),
                        "archaeology_matches": finding.get("matches", []),
                        "grimoire_chapters": finding.get("anthropology", {}).get("chapters", [])
                    }
                )
                processed += 1
            except Exception as e:
                logger.error(f"Failed to process finding: {e}")
                
    return {"status": "success", "processed": processed}

def create_daily_wisdom_digest() -> str:
    """Generate a summary of recently recovered wisdom."""
    from whitemagic.core.memory.unified import get_unified_memory
    unified = get_unified_memory()
    
    recent = unified.search(query="recovered", limit=5, memory_type="long_term")
    if not recent:
        return "No new wisdom recovered today."
        
    digest = "# Daily Wisdom Digest\n\n"
    for mem in recent:
        digest += f"## {mem.title}\n"
        digest += f"**Source:** {mem.metadata.get('original_path', 'unknown')}\n\n"
        digest += f"{mem.content[:300]}...\n\n"
        
    output_path = Path(PROJECT_ROOT) / "core_system" / "data" / f"wisdom_digest_{datetime.now().strftime('%Y%m%d')}.md"
    output_path.write_text(digest)
    return str(output_path)

def wisdom_report() -> str:
    return get_archaeologist().reading_report()

__all__ = [
    "ChariotArchaeologist",
    "WisdomExtractor",
    "create_daily_wisdom_digest",
    "extract_wisdom",
    "find_unread",
    "get_archaeologist",
    "get_wisdom_extractor",
    "mark_read",
    "mark_read_async",
    "mark_written",
    "mark_written_async",
    "process_wisdom_archives",
    "stats",
    "wisdom_report",
]

# Compatibility aliases
def mark_read_async(*args, **kwargs): return mark_read(*args, **kwargs)
def mark_written_async(*args, **kwargs): return mark_written(*args, **kwargs)
def extract_wisdom(content: str, source: str): return get_wisdom_extractor().extract_wisdom(content, source)
