#!/usr/bin/env python3
"""
StartupLX Daily Priority Filter
Usage: python3 scripts/priority_filter.py --today
"""

import json
import os
from datetime import datetime

def read_obsidian_progress():
    """Read current progress from Obsidian daily notes"""
    vault_path = os.path.expanduser("~/Vaults/cyprian-obsidian/cyprian")
    today = datetime.now().strftime("%Y-%m-%d")
    
    try:
        with open(f"{vault_path}/Daily/{today}.md") as f:
            content = f.read()
            # Extract revenue, targets, completed tasks
            return {
                "revenue": extract_revenue(content),
                "target": 7000,
                "completed_tasks": extract_completed(content),
                "website_status": extract_website_status(content)
            }
    except:
        return {"revenue": 0, "target": 7000, "completed_tasks": [], "website_status": "not_deployed"}

def extract_revenue(content):
    """Extract current revenue from daily note"""
    import re
    match = re.search(r"Current.*?(?:Pipeline|Revenue|MRR).*?\$(\d+)", content, re.IGNORECASE)
    return int(match.group(1)) if match else 0

def extract_completed(content):
    """Extract completed tasks"""
    import re
    return re.findall(r"- \[x\] (.+)", content)

def extract_website_status(content):
    """Extract website deployment status"""
    return "deployed" if "website" in content.lower() and "live" in content.lower() else "not_deployed"

def filter_priorities(progress):
    """Filter and rank priorities by revenue impact"""
    
    targets = {
        "weekly_target": 800,
        "mrr_target": 7000,
        "active_projects_max": 2
    }
    
    # Revenue-based filtering
    if progress["revenue"] < targets["weekly_target"] * 0.5:
        return {
            "priority": "CRITICAL_CLIENT_OUTREACH",
            "tasks": [
                {"rank": 1, "action": "Send 5 verified outreach emails", "impact": "Generates $2000+ pipeline"},
                {"rank": 2, "action": "Follow up on pending leads", "impact": "Convert 1-2 responses to $500-$1500"},
                {"rank": 3, "action": "Write 2 proposal drafts", "impact": "Ready for immediate sending"},
                {"rank": 4, "action": "Deploy contact page", "impact": "Capture inbound leads"},
                {"rank": 5, "action": "Connect Calendly to Typeform", "impact": "Enable booking funnel"}
            ],
            "reasoning": f"Revenue ${progress['revenue']}/${targets['weekly_target']}/week - prioritize income generation"
        }
    
    elif progress["website_status"] == "not_deployed":
        return {
            "priority": "HIGH_WEBSITE_DEPLOYMENT",
            "tasks": [
                {"rank": 1, "action": "Deploy website homepage", "impact": "Online presence + lead capture"},
                {"rank": 2, "action": "Add booking integration", "impact": "Convert visitors to clients"},
                {"rank": 3, "action": "Connect Stripe checkout", "impact": "Enable instant payments"},
                {"rank": 4, "action": "Send 3 outreach emails", "impact": "Maintain client pipeline"}
            ],
            "reasoning": "Website not live - need income capture point"
        }
    
    else:
        return {
            "priority": "MEDIUM_AUTOMATION_SCALING",
            "tasks": [
                {"rank": 1, "action": "Update Metabase dashboard", "impact": "Real-time business visibility"},
                {"rank": 2, "action": "Close 1 client proposal", "impact": "Generate $500-1500 revenue"},
                {"rank": 3, "action": "Automate invoice generation", "impact": "Reduce manual billing work"},
                {"rank": 4, "action": "Write proposal for second client", "impact": "Build $2000 pipeline"}
            ],
            "reasoning": f"System live with ${progress['revenue']}/week revenue - optimize and scale"
        }

def main():
    progress = read_obsidian_progress()
    priorities = filter_priorities(progress)
    
    print(json.dumps({
        "status": "success",
        "progress": progress,
        "priorities": priorities,
        "timestamp": datetime.now().isoformat()
    }, indent=2))

if __name__ == "__main__":
    main()