import os
import sys
from dotenv import load_dotenv

# Ensure we can import from the project root
sys.path.append(os.getcwd())

from slack_bot.obsidian.indexer import ObsidianIndexer
from slack_bot.llm.gemini import GeminiLLM
from health.utils.logging_config import setup_logger

logger = setup_logger(__name__)

class ObsidianDistiller:
    def __init__(self):
        load_dotenv()
        self.vault_path = os.getenv("OBSIDIAN_VAULT_PATH")
        if not self.vault_path:
            raise ValueError("OBSIDIAN_VAULT_PATH not found in .env")
            
        self.indexer = ObsidianIndexer(self.vault_path)
        # Using a higher-tier model if possible for better analysis, 
        # but defaulting to the configured one.
        self.llm = GeminiLLM(system_instruction="You are an expert analyst and ghostwriter. Your goal is to synthesize the essence of a user's writing style, business philosophy, and core projects from a collection of their personal notes.")

    def run(self):
        logger.info("Starting Obsidian Distillation...")
        self.indexer.scan_vault()
        
        writing_samples = self.indexer.get_writing_samples(count=50) # Get all up to 50
        reply_samples = self.indexer.get_reply_samples(count=50)
        
        all_samples = writing_samples + reply_samples
        
        if not all_samples:
            logger.warning("No tagged samples found. Add #writing_sample or #reply_sample to your notes.")
            return

        logger.info(f"Analyzing {len(all_samples)} samples...")
        
        # Combine samples with clear delimiters
        compiled_text = "\n\n".join(all_samples)
        
        distill_prompt = f"""Below is a collection of my personal notes, articles, and speech drafts. 
Please analyze them deeply and provide a "Distillation Report" in Chinese.

### GOALS:
1. **StyleDNA**: Extract my unique writing style. (Sentence structure, tone, bilingual habits, degree of technicality).
2. **Glossary & Concepts**: Identify recurring project names (e.g. XLSmart, Lighthouse), technical terms, and "internal slang". Define them based on the context.
3. **Core Philosophy**: Summarize my management values, product philosophy (e.g. "IT Babel Tower"), and decision frameworks.
4. **Actionable Instructions**: Provide concrete "System Instructions" I can use for a LLM bot to mimic me perfectly.

### SAMPLES:
{compiled_text}

### FINAL REPORT:
Provide the output in Markdown format.
"""

        try:
            # We use Generate Response with a long prompt. 
            # Note: 27 samples might be large, but Gemini-1.5 handles this.
            response, _ = self.llm.generate_response(distill_prompt, context=[])
            
            output_path = "distilled_insights.md"
            with open(output_path, "w", encoding="utf-8") as f:
                f.write(response)
                
            logger.info(f"Distillation complete! Report saved to {output_path}")
            print(f"\nDistillation complete! Please check '{output_path}'")
            
        except Exception as e:
            logger.error(f"Distillation failed: {e}")
            print(f"Error: {e}")

if __name__ == "__main__":
    distiller = ObsidianDistiller()
    distiller.run()
