import http.server
import json
import os
import sys
import threading
import time
from pathlib import Path
from urllib.parse import urlparse, parse_qs

PORT = 8080
PIPELINE_SCRIPT = "seo_pipeline.py"
running_tasks = {}

def run_pipeline_for_days(days):
    global running_tasks
    if days in running_tasks and running_tasks[days] == "running":
        return
    running_tasks[days] = "running"
    print(f"Pipeline gestartet fuer {days} Tage...", flush=True)
    try:
        import subprocess
        result = subprocess.run(
            [sys.executable, PIPELINE_SCRIPT, "--days", str(days)],
            capture_output=True, text=True, timeout=600
        )
        if result.returncode == 0:
            print(f"Pipeline fertig: {days} Tage", flush=True)
            running_tasks[days] = "done"
        else:
            print(f"Pipeline Fehler: {result.stderr[-500:]}", flush=True)
            running_tasks[days] = "error"
    except subprocess.TimeoutExpired:
        running_tasks[days] = "timeout"
    except Exception as e:
        running_tasks[days] = "error"

class DashboardHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        parsed = urlparse(self.path)
        path = parsed.path
        params = parse_qs(parsed.query)

        # Startseite -> Dashboard
        if path == "/" or path == "":
            self.path = "/PottSEO_Dashboard_LIVE.html"
            return super().do_GET()

        if path == "/api/refresh":
            days = int(params.get("days", [30])[0])
            json_file = f"clients_data_{days}d.json"
            if Path(json_file).exists():
                age = time.time() - os.path.getmtime(json_file)
                if age < 3600:
                    self.send_json({"status": "cached", "age_minutes": round(age/60, 1)})
                    return
            thread = threading.Thread(target=run_pipeline_for_days, args=(days,))
            thread.daemon = True
            thread.start()
            self.send_json({"status": "started", "days": days})
            return

        if path == "/api/status":
            days = int(params.get("days", [30])[0])
            status = running_tasks.get(days, "idle")
            json_file = f"clients_data_{days}d.json"
            has_data = Path(json_file).exists()
            age = round((time.time() - os.path.getmtime(json_file)) / 60, 1) if has_data else None
            self.send_json({"status": status, "has_data": has_data, "age_minutes": age, "days": days})
            return

        if path == "/api/refresh-all":
            for days in [1, 7, 30, 90, 365]:
                thread = threading.Thread(target=run_pipeline_for_days, args=(days,))
                thread.daemon = True
                thread.start()
                time.sleep(0.5)
            self.send_json({"status": "started", "ranges": [1, 7, 30, 90, 365]})
            return

        return super().do_GET()

    def send_json(self, data):
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Access-Control-Allow-Origin", "*")
        self.end_headers()
        self.wfile.write(json.dumps(data).encode())

    def log_message(self, format, *args):
        msg = format % args
        if "/api/" in msg or "404" in msg or "500" in msg:
            print(f"  {msg}", flush=True)

def main():
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    print("=" * 50, flush=True)
    print("  PottSEO Dashboard Server", flush=True)
    print(f"  Port: {PORT}", flush=True)
    print("=" * 50, flush=True)
    server = http.server.HTTPServer(("", PORT), DashboardHandler)
    server.serve_forever()

if __name__ == "__main__":
    main()
